Uncommon Words from Two Sentences — LeetCode 884 Python Solution
- Problem
- #884
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Python solution
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
cnt = Counter(s1.split()) + Counter(s2.split())
return [s for s, v in cnt.items() if v == 1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(m + n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 884. Uncommon Words from Two Sentences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 884. Uncommon Words from Two Sentences?
- LeetCode 884. Uncommon Words from Two Sentences is rated Easy on LeetCode.
- What is the time complexity of LeetCode 884. Uncommon Words from Two Sentences?
- The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 884. Uncommon Words from Two Sentences?
- The Python solution on this page uses O(m + n) auxiliary space.
- What topics does LeetCode 884. Uncommon Words from Two Sentences cover?
- LeetCode 884. Uncommon Words from Two Sentences is tagged Hash Table, String and Counting on LeetCode.