Uncommon Words from Two Sentences (LeetCode 884): Solution and Explanation

Easy
Hash Table
String
Counting

Return every word that appears exactly once in one sentence and not at all in the other. The answer can be in any order.

Intuition

The definition talks about two sentences, but it collapses to one condition. Once in s1 and zero times in s2 gives a total of 1. Zero in s1 and once in s2 also gives 1.

Every other case gives a different total: a word repeated inside one sentence, or a word shared by both, reaches at least 2. A word in neither sentence is not a candidate at all.

So the word is uncommon exactly when its count over both sentences combined is 1. That turns the problem into plain word counting on the joined text.

One pass fills a hash map, a second pass over the map collects the words with count 1.

Approach: Count words over both sentences

  1. Join the sentences with a space and split into words.
  2. Increment count[w] for every word.
  3. Collect every word whose count is exactly 1.
  4. Return the collected words in any order.

Step-by-step example

s1 = "this apple is sweet", s2 = "this apple is sour"
  1. Counting s1: this, apple, is and sweet each get count 1.
  2. Counting s2: this, apple and is rise to 2. sour is new and gets 1.
  3. Filter the map: this, apple and is have count 2 and are skipped.
  4. sweet and sour have count 1 and are kept.
  5. Return ["sweet","sour"].

Code: Python, Java, C++

1class Solution:
2    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
3        count = {}
4        for w in (s1 + ' ' + s2).split():
5            count[w] = count.get(w, 0) + 1
6        res = []
7        for w, c in count.items():
8            if c == 1:
9                res.append(w)
10        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

Splitting and hashing touch every character of both sentences a constant number of times, and the filter pass is linear in the number of distinct words.

Space

O(n + m)

The map can hold every distinct word from both sentences.

Other approaches

Two separate maps (time O(n + m), space O(n + m))

Count s1 and s2 in their own maps, then keep words with count 1 in one map and 0 in the other. It follows the definition literally but does the same work with more code.

Sort the combined word list (time O(w log w) comparisons for w words, space O(w))

Sort all words, then keep the ones whose neighbours differ from them. Equal words become adjacent, so runs of length 1 are the answer.

Common mistakes

  • Taking the symmetric difference of the two word sets. A word that appears twice in s1 and never in s2 is in that difference but is not uncommon.
  • Counting each sentence separately and checking only the other sentence. Repeats inside the same sentence also disqualify a word.
  • Splitting on spaces when a sentence could be empty or have extra spaces. The constraints rule this out here, but split() with no argument in Python, or strings.Fields in Go, is safer.
  • Expecting a fixed order. Any order is accepted, and hash map iteration order differs between languages.

Frequently asked questions

Why is a combined count of 1 enough?

A count of 1 means the word occurs once in total, so it is in exactly one sentence, exactly once, and absent from the other. That is precisely the definition of uncommon.

Does the order of the output matter?

No. Any order is accepted, so the judge compares the answer as an unordered list.

What if every word is shared?

Then every count is at least 2 and the answer is an empty list.