The Weekly Challenge 385

Uncommon Words and Outermost Parentheses

Task 1: Uncommon Words

Given two sentences, find all words that appear exactly once in one sentence and do not appear in the other sentence.

Example Output

Input: $s1 = "this apple is sweet", $s2 = "this apple is sour" Output: ("sour", "sweet")

Logic

Tokenize and count the frequency of all words across both sentences combined. Words with a total occurrence count of exactly 1 are the uncommon words.

Perl Solution

ch-1.pl

sub uncommon_words ( $sentence1, $sentence2 ) { my %count; for my $w ( split( /\s+/, "$sentence1 $sentence2" ) ) { $count{$w}++; } my @result = grep { $count{$_} == 1 } keys %count; return [ sort @result ]; }

Python Solution

ch-1.py

def uncommon_words(sentence1: str, sentence2: str) -> list[str]: """Find words appearing exactly once across both sentences.""" counts = Counter((sentence1 + " " + sentence2).split()) return sorted([w for w, c in counts.items() if c == 1])

Task 2: Outermost Parentheses

Given a valid parentheses string, remove the outermost parentheses of every primitive decomposed substring.

Example Output

Input: $str = "(()())(())" Output: "()()()"

Logic

Track the depth/balance of open parentheses. When encountering '(' at depth > 0, include it and increment depth; when encountering ')' at depth > 1, include it and decrement depth.

Perl Solution

ch-2.pl

sub remove_outermost_parentheses ($str) { my $result = ''; my $balance = 0; for my $char ( split //, $str ) { if ( $char eq '(' ) { $result .= '(' if $balance > 0; $balance++; } elsif ( $char eq ')' ) { $balance--; $result .= ')' if $balance > 0; } } return $result; }

Python Solution

ch-2.py

def remove_outermost_parentheses(s: str) -> str: """Remove outermost parentheses from each primitive component.""" result: list[str] = [] balance = 0 for ch in s: if ch == "(": if balance > 0: result.append("(") balance += 1 elif ch == ")": balance -= 1 if balance > 0: result.append(")") return "".join(result)