Uncommon Words from Two Sentences - Problem

Ever wondered how to find the unique elements between two collections? This problem asks you to identify uncommon words between two sentences.

Given two sentences s1 and s2, where each sentence contains lowercase words separated by single spaces, you need to find all words that appear exactly once in either sentence but not in both.

A word is considered uncommon if:

  • It appears exactly once in one sentence, AND
  • It doesn't appear at all in the other sentence

Example: If s1 = "this apple is sweet" and s2 = "this apple is sour", then ["sweet", "sour"] are uncommon words.

Return the result in any order.

Input & Output

example_1.py โ€” Basic Case
$ Input: s1 = "this apple is sweet", s2 = "this apple is sour"
โ€บ Output: ["sweet", "sour"]
๐Ÿ’ก Note: Both 'sweet' and 'sour' appear exactly once in their respective sentences and don't appear in the other sentence, making them uncommon.
example_2.py โ€” Repeated Words
$ Input: s1 = "apple apple", s2 = "banana"
โ€บ Output: ["banana"]
๐Ÿ’ก Note: 'apple' appears twice in s1, so it's not uncommon. 'banana' appears exactly once and only in s2, making it uncommon.
example_3.py โ€” No Uncommon Words
$ Input: s1 = "apple apple", s2 = "apple apple"
โ€บ Output: []
๐Ÿ’ก Note: 'apple' appears multiple times across both sentences, so there are no uncommon words.

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
  • Both sentences contain at least one word

Visualization

Tap to expand
Restaurant Menu Comparison๐Ÿฝ๏ธ Restaurant Aโ€ข pasta (popular)โ€ข pizza (popular)โ€ข salad (popular)โ€ข tiramisu (signature)๐Ÿฝ๏ธ Restaurant Bโ€ข pasta (popular)โ€ข pizza (popular)โ€ข salad (popular)โ€ข cheesecake (signature)๐Ÿ“Š Frequency Counterpasta: 2 (common)pizza: 2 (common)salad: 2 (common)tiramisu: 1 โญcheesecake: 1 โญ๐ŸŽฏ Signature Dishes Found!tiramisu (Restaurant A) + cheesecake (Restaurant B)
Understanding the Visualization
1
Combine Menus
List all dishes from both restaurant menus together
2
Count Dish Frequency
Count how many times each dish appears across both menus
3
Find Signature Dishes
Dishes appearing exactly once are the unique signatures of each restaurant
Key Takeaway
๐ŸŽฏ Key Insight: Just like signature restaurant dishes, words appearing exactly once across both sentences are automatically uncommon - they're unique to one context and can't be shared!
Asked in
Google 15 Amazon 12 Meta 8 Apple 6
85.0K Views
Medium Frequency
~15 min Avg. Time
2.1K 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