NeetCode #133LC-884EasyArrays & Hashing
← Back to All Problems#133 · #884 · Uncommon Words from Two Sentences(两句话中的不常见单词)
📌 Problem Statement & Constraints
A word is uncommon if it appears exactly once in either of the two sentences and does not appear in the other. Given two sentences
s1 and s2, return a list of all uncommon words. Constraints: 1 <= s1.length, s2.length <= 200; sentences contain lowercase letters and single spaces.💡 Core Algorithmic Approaches
- Concatenate the two sentences and count the frequency of every word.
- Words occurring exactly once across the combined text are precisely the uncommon ones -- a word appearing in both sentences would have a count of at least 2.
- Collect the words with count 1.
- This single-counter approach elegantly avoids tracking the two sentences separately.
💻 Benchmark Python3 Implementation
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
from collections import Counter
cnt = Counter((s1 + " " + s2).split())
return [w for w, c in cnt.items() if c == 1] # count 1 in the union⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + m): splitting and counting are linear in the total text length.
💾 Space Complexity
O(n + m) for the counter.
⚠️ Interview Pitfalls & Follow-ups
- Building two separate counters and taking the difference: it works, but you would still need to filter words with count 1 within each sentence; the combined counter does both jobs at once.
- Forgetting the separating space when concatenating:
"ab" + "cd"would merge two words into one. Uses1 + " " + s2. - Using
set(s1.split()) ^ set(s2.split()): this loses multiplicity, so a word appearing twice ins1and not at all ins2would be wrongly included. - Assuming words are unique within a sentence: they are not, which is exactly what the count-1 filter handles.