File: uncommon-words-from-two-sentences/solution.py

Date: 2026-06-06

Time: 19:35

uncommon-words-from-two-sentences/solution.py

Purpose

This file solves LeetCode 884 — Uncommon Words from Two Sentences. It owns the single function uncommonfromsentences, which identifies words that appear exactly once across two input sentences combined. It follows the repo's convention of one solution file per problem directory.

Key Components

uncommonfromsentences(s1: str, s2: str) -> List[str] — The sole public function. Takes two space-separated sentences and returns all words whose total frequency across both sentences is exactly 1.

The contract is simple: a word is "uncommon" if and only if it appears exactly once in the union of both sentences. This means a word appearing twice in one sentence (and zero times in the other) is *not* uncommon — the counting is global, not per-sentence.

Patterns

The solution uses a count-and-filter idiom: build a frequency map, then select entries matching a predicate. This is the canonical approach for frequency-based selection problems in this repo.

The key insight is concatenating the sentences before splitting ((s1 + " " + s2).split()), which collapses the two-sentence problem into a single-counter problem. This works because the definition of "uncommon" is a global frequency of exactly 1 — there's no need to track which sentence a word came from.

Dependencies

Imports:

Imported by: The testsolution.py in the same directory, plus hundreds of other test files across the repo (the "Imported By" list in the prompt is misleading — those test files import their *own* solution modules, not this one; only uncommon-words-from-two-sentences/testsolution.py actually imports this function).

Flow

1. Concatenate s1 and s2 with a space separator

2. Split into a word list via str.split() (splits on any whitespace, discards empty strings)

3. Pass the list to Counter, producing a {word: count} mapping

4. List comprehension filters to words where count == 1

The entire computation is a single expression chain — no intermediate state, no mutation.

Invariants

Error Handling

None. The function trusts its inputs conform to the LeetCode spec. Passing None would raise TypeError at the concatenation. Non-string inputs are not guarded against — appropriate for a LeetCode solution where inputs are guaranteed.

Topics to Explore

Beliefs