Daily Leetcode Question 17/09/2024 - 884. Uncommon Words from Two Sentences
Problem Description:
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. Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.
Solution:
from typing import List
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
s1_counter = Counter(s1.split())
s2_counter = Counter(s2.split())
combined_counter = s1_counter + s2_counter
return [word for word in combined_counter if combined_counter[word] == 1]
Explanation:
We can solve this by finding all the unique words in the occurrences of all words in both sentences.
This ensures that the words we found are unique in the original sentence AND in the other sentence.
def uncommonFromSentences(s1, s2):
s1_counter = Counter(s1.split())
s2_counter = Counter(s2.split())
combined_counter = s1_counter + s2_counter
return [word for word in combined_counter if combined_counter[word] == 1]
The time complexity is O(n + m) where n is the number of words s1 has and m the number of words s2 has. Creating the Counter() object thus takes O(n + m) time.
The space complexity is also O(n + m) as the worst case scenario being all words are unique.
The full solution can be found near the top of the page.