Task 1: Uncommon Words
You are given two sentences, $line1 and $line2.
Write a script to find all uncommon words in any order in the given two sentences. Return ('') if none found.
A word is uncommon if it appears exactly once in one of the sentences and doesn't appear in the other sentence.
Example 1: Input: $line1 = 'Mango is sweet', $line2 = 'Mango is sour' → Output: ('sweet', 'sour')
Example 2: Input: $line1 = 'Mango Mango', $line2 = 'Orange' → Output: ('Orange')
Example 3: Input: $line1 = 'Mango is Mango', $line2 = 'Orange is Orange' → Output: ('')
Method Explanation
The problem asks us to identify words that satisfy two specific conditions:
- The word must appear exactly once in either
$line1or$line2. - The word must not appear at all in the opposite sentence.
A clean and efficient approach is to build frequency tables (hash tables or counters) for both sentences:
- Tokenize each sentence into words by splitting on whitespace.
- Count the occurrences of each word in two separate frequency maps,
count1andcount2. - Iterate through the words of the first sentence and select those where
count1[word] == 1andwordis not incount2. - Similarly, iterate through the words of the second sentence and select those where
count2[word] == 1andwordis not incount1. - If the resulting list is non-empty, return it; otherwise return a singleton with an empty string
('')as specified.
This solution runs in linear time $O(L_1 + L_2)$ where $L_1$ and $L_2$ are the lengths of the sentences, with auxiliary space proportional to the unique words in each sentence.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
signature_for uncommon_words => (
method => 0,
positional => [ Str, Str ],
);
sub uncommon_words ( $line1, $line2 ) {
my %count1;
my @words1 = split ' ', $line1;
$count1{$_}++ for @words1;
my %count2;
my @words2 = split ' ', $line2;
$count2{$_}++ for @words2;
my @result;
for my $word ( grep { $count1{$_} == 1 && !exists $count2{$_} } @words1 ) {
push @result, $word;
}
for my $word ( grep { $count2{$_} == 1 && !exists $count1{$_} } @words2 ) {
push @result, $word;
}
return @result ? @result : ('');
}
Python Solution
from collections import Counter
def uncommon_words(line1: str, line2: str) -> tuple[str, ...]:
"""Find all uncommon words in any order in the given two sentences."""
words1 = line1.split()
words2 = line2.split()
counter1 = Counter(words1)
counter2 = Counter(words2)
uncommon: list[str] = [
word for word in counter1 if counter1[word] == 1 and word not in counter2
]
for word in counter2:
if counter2[word] == 1 and word not in counter1:
uncommon.append(word)
return tuple(uncommon) if uncommon else ("",)