Uncommon Words from Two Sentences
Question
We are given two sentences
A
andB
. (A sentence is a string of space separated words. 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.
Return a list of all uncommon words.
You may return the list in any order.
Example 1: Input: A = "this apple is sweet", B = "this apple is sour" Output: ["sweet","sour"]
Example 2: Input: A = "apple apple", B = "banana" Output: ["banana"]
Note:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
both contain only spaces and lowercase letters.
Approach 1: Counting
Intuition and Algorithm
Every uncommon word occurs exactly once in total. We can count the number of occurrences of every word, then return ones that occur exactly once.
1 | class Solution: |
- Runtime: 32 ms, faster than 99.14% of Python3 online submissions for Uncommon Words from Two Sentences.
- Memory Usage: 13.3 MB, less than 23.76% of Python3 online submissions for Uncommon Words from Two Sentences.
Approach 2: Counting (Original)
Intuition and Algorithm
Every uncommon word occurs exactly once in total. We can count the number of occurrences of every word, then return ones that occur exactly once.
1 | class Solution: |
Runtime: 36 ms, faster than 92.30% of Python3 online submissions for Uncommon Words from Two Sentences.
Memory Usage: 13.1 MB, less than 75.47% of Python3 online submissions for Uncommon Words from Two Sentences.