Problem Description
Given two sentences s1 and s2, return a list of all the uncommon words. A word is considered uncommon if it appears exactly once in one sentence and does not appear in the other. Each sentence is a string of single-space separated words.
Key Insights
- Split each sentence into words using space as a delimiter.
- Use a hash table to count the frequency of each word across both sentences.
- Identify the uncommon words by filtering those that have a frequency of exactly one.
- This approach is efficient given the constraint of relatively short sentences.
Space and Time Complexity
Time Complexity: O(n + m), where n and m are the number of words in s1 and s2 respectively. Space Complexity: O(k), where k is the number of distinct words across both sentences.
Solution
The solution splits both sentences into their constituent words and uses a hash map to count the occurrence of each word. After building the frequency table, the algorithm iterates through the map to retrieve all words that have a frequency of 1. These words are the uncommon words as defined by the problem. The use of a hash map allows for efficient insertion and lookup, ensuring that the solution remains optimal.