Task 1: Match String
"Needle in a Word Stack: Finding Embedded Strings!"
This week's first task asks us to scan an array of strings and return every string that appears as a substring of another string in the same array. The order must follow the original input order, and the examples also show that duplicate matches should only appear once in the output.
The Strategy: Walk through the list in order, skip words already seen, and for each remaining word check whether it appears inside any other word in the array. As soon as we find one containing word, we add the candidate to the result and move on. This preserves first-occurrence order while de-duplicating repeated inputs.
Perl Implementation
sub match_string ($words) {
($words) = $WORDS_CHECK->($words);
my %seen;
my @result;
for my $i ( 0 .. $#$words ) {
my $word = $words->[$i];
next if $seen{$word}++;
for my $j ( 0 .. $#$words ) {
next if $i == $j;
if ( index( $words->[$j], $word ) >= 0 ) {
push @result, $word;
last;
}
}
}
return \@result;
}
Python Implementation
def match_string(words: Sequence[str]) -> list[str]:
"""
Return words that occur as substrings of other words, in first-occurrence order.
Duplicate inputs are returned only once.
"""
result: list[str] = []
seen: set[str] = set()
for idx, word in enumerate(words):
if word in seen:
continue
seen.add(word)
for other_idx, other in enumerate(words):
if other_idx == idx:
continue
if word in other:
result.append(word)
break
return result