Given two sentences s1
and s2
, return a list of all the uncommon words. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet","sour"]
str.split()
method to break sentences into lists of words.from collections import Counter
def uncommonFromSentences(s1, s2):
# Split the sentences into words
words_s1 = s1.split()
words_s2 = s2.split()
# Count the occurrences of each word
word_count = Counter(words_s1 + words_s2)
# Extract words which have exactly one occurrence
uncommon_words = [word for word, count in word_count.items() if count == 1]
return uncommon_words
# Example usage:
s1 = "this apple is sweet"
s2 = "this apple is sour"
print(uncommonFromSentences(s1, s2)) # Output: ["sweet", "sour"]
O(n + m)
where n
is the length of s1
and m
is the length of s2
.O(n + m)
because each word insertion/check in hashmap is O(1)
on average, and we have n + m
words in total.n + m
entries resulting in O(n + m)
.Therefore, the overall time complexity is O(n + m)
. The space complexity is also O(n + m)
due to the storage used for splitting words and the hashmap for counting occurrences.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?