Uncommon Words from Two Sentences - Problem

A sentence is a string of single-space separated words where each word consists only of lowercase letters.

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet", "sour"]
💡 Note: Words "this", "apple", "is" appear in both sentences. Only "sweet" and "sour" appear exactly once.
Example 2 — Single Word Sentences
$ Input: s1 = "apple", s2 = "banana"
Output: ["apple", "banana"]
💡 Note: Both words appear exactly once, so both are uncommon.
Example 3 — Repeated Words
$ Input: s1 = "a a", s2 = "b b"
Output: []
💡 Note: Word 'a' appears twice in s1, word 'b' appears twice in s2. No word appears exactly once.

Constraints

  • 1 ≤ s1.length, s2.length ≤ 200
  • s1 and s2 consist of lowercase English letters and spaces
  • s1 and s2 do not have leading or trailing spaces
  • All words in s1 and s2 are separated by a single space

Visualization

Tap to expand
Uncommon Words from Two Sentences INPUT s1: "this apple is sweet" this apple is sweet s2: "this apple is sour" this apple is sour Common words Unique in s1 Unique in s2 ALGORITHM STEPS 1 Combine Sentences Merge s1 and s2 into one word list 2 Build Hash Map Count frequency of each word HashMap "this" : 2 "apple" : 2 "is" : 2 "sweet" : 1 "sour": 1 3 Filter Count == 1 Keep only words with frequency exactly 1 4 Return Result Output uncommon words as list FINAL RESULT Uncommon Words Found: "sweet" from s1 "sour" from s2 Output Array: ["sweet", "sour"] OK - Verified! Both words appear exactly once total "sweet" only in s1 "sour" only in s2 Both counted once Key Insight: A word is "uncommon" if it appears exactly ONCE across BOTH sentences combined. By merging both sentences and counting word frequencies with a hash map, we can identify uncommon words in O(n) time where n = total number of words. TutorialsPoint - Uncommon Words from Two Sentences | Hash Map Approach
Asked in
Amazon 15 Google 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen