Uncommon Words from Two Sentences
Easy · Arrays & Hashing · Explanation and code example
Hash Map - II
How it works
This is a more concise version of the same approach. We use built-in functions like Counter (in Python) or stream operations (in Java) to reduce boilerplate while maintaining the same logic.
Steps
- Combine and split both sentences into words.
- Count word frequencies using a built-in counter or grouping function.
- Filter to keep only words with count equal to
1. - Return the filtered words.
Complexity
- Time complexity:
O(n + m) - Space complexity:
O(n + m)
Where
nandmare the lengths of the stringss1ands2, respectively.
Things to watch for
Misunderstanding "Uncommon" Definition
A word is uncommon if it appears exactly once across both sentences combined, not once per sentence. Some mistakenly check if a word appears in one sentence but not the other, which is incorrect. A word appearing twice in the same sentence is also not uncommon.
Incorrect String Splitting
When splitting sentences into words, be careful with edge cases like multiple spaces or empty strings. The problem guarantees single spaces between words, but forgetting to handle the concatenation properly (e.g., not adding a space between s1 and s2) can cause words at the boundary to merge incorrectly.
Python code example
from typing import List
from collections import Counter
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
return [w for w, cnt in Counter(s1.split(" ") + s2.split(" ")).items() if cnt == 1]
C++ code example
class Solution {
public:
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string, int> count;
istringstream ss(s1 + " " + s2);
string w;
while (ss >> w) {
count[w]++;
}
vector<string> res;
for (auto& [w, c] : count) {
if (c == 1) {
res.push_back(w);
}
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.