Task 1: Common Characters
"Intersect All: What Characters Share Every Word?"
Given an array of lowercase words, return every character that appears in each word, preserving multiplicity.
The Strategy: Build a frequency map from the first word. For each subsequent word, update to the minimum count per character. Remove characters with zero count. The result repeats each remaining character by its minimum frequency.
Perl Implementation
sub common_characters {
my (@words) = @_;
return () if !@words;
my %common;
$common{$_}++ for split //, $words[0];
for my $word ( @words[ 1 .. $#words ] ) {
my %freq;
$freq{$_}++ for split //, $word;
for my $char ( keys %common ) {
$common{$char} = exists $freq{$char}
? min( $common{$char}, $freq{$char} ) : 0;
}
delete @common{ grep { $common{$_} == 0 } keys %common };
}
my @result;
for my $char ( sort keys %common ) {
push @result, ($char) x $common{$char};
}
return @result;
}
Python Implementation
from collections import Counter
def common_characters(words: list[str]) -> list[str]:
"""Characters common to all words, preserving multiplicity."""
if not words:
return []
common = Counter(words[0])
for word in words[1:]:
freq = Counter(word)
for ch in list(common):
if ch in freq:
common[ch] = min(common[ch], freq[ch])
else:
del common[ch]
return sorted(common.elements())