The Weekly Challenge 315

Find Words & Find Third!

Original Challenge Link | Solutions on GitHub

Task 1: Find Words

"Index Hunt: Where's the Character?"

Given a list of words and a character, return the indices (0-based) of all words that contain the given character.

The Strategy: Iterate over the list of words with their indices. For each word, check if the given character appears in it (using index or contains). Collect all matching indices and return them as an array.
Perl Implementation
sub find_words ($char, $words) {
    ( $char, $words ) = $ARGS_CHECK->( $char, $words );
    die 'Expected a single character' if length($char) != 1;

    my @idx;
    for my $i ( 0 .. $#$words ) {
        push @idx, $i if index( $words->[$i], $char ) >= 0;
    }
    return \\@idx;
}
Python Implementation
def find_words(char: str, words: list[str]) -> list[int]:
    """Return indices of words containing the given character."""
    if len(char) != 1:
        raise ValueError("Expected a single character")
    return [i for i, w in enumerate(words) if char in w]

Task 2: Find Third

"Sequence Spotter: Find the Word After a Pair"

Given a sentence (string of words separated by spaces) and two words, return all words that immediately follow an occurrence of the two words in sequence.

The Strategy: Split the sentence into words. Iterate over the words from the start up to the third-to-last word. For each position i, check if words[i] equals the first target word and words[i+1] equals the second target word. If so, collect words[i+2] (if it exists). Return all collected words.
Perl Implementation
sub find_third {
    my ($sentence, $w1, $w2) = @_;
    my @words = split /\\s+/, $sentence;
    my @result;
    for my $i (0 .. $#words - 2) {
        if ($words[$i] eq $w1 && $words[$i+1] eq $w2) {
            push @result, $words[$i+2];
        }
    }
    return @result;
}
Python Implementation
def find_third(sentence: str, w1: str, w2: str) -> list[str]:
    """Return words that immediately follow the sequence w1, w2 in the sentence."""
    words = sentence.split()
    result = []
    for i in range(len(words) - 2):
        if words[i] == w1 and words[i+1] == w2:
            result.append(words[i+2])
    return result