Finding Uncommon Words Between Two Sentences Using Hash Maps in C++
Intuition\n Describe your first thoughts on how to solve this problem. \n- To solve the problem of finding uncommon words between two sentences, we need to iden
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To solve the problem of finding uncommon words between two sentences, we need to identify words that appear exactly once in one sentence and do not appear in the other. Here\u2019s how I would think through the problem:\n\n1.  Count Occurrences: First, we need to count the occurrences of each word in both sentences. This will help us determine which words are unique to each sentence.\n\n2.  Combine Counts: By combining counts from both sentences, we can identify words that are unique to one sentence and do not appear in the other.\n\n3. Filter Uncommon Words: Finally, we\'ll filter the words that appear exactly once in one sentence but not in the other.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Count Frequencies: Use an unordered map (hash map) to store the frequency of each word from both sentences. This will allow us to efficiently count the occurrences and later query the counts.\n\n- Parse Sentences: Use istringstream to split each sentence into words and update their counts in the hash map.\n\n- Identify Uncommon Words: After counting the frequencies, iterate through the hash map to find words that have a count of exactly one and ensure they are not present in the other sentence.\n# Complexity\n- Time complexity:$$O(n + m)$$ where n is the number of words in the first sentence and m is the number of words in the second sentence.\n\n\n- Space complexity: The space complexity is $$O(n + m)$$ as well, due to the storage of word counts in the hash map, where n and m are the number of unique words in each sentence.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    vector<string> uncommonFromSentences(string s1, string s2) {\n        unordered_map<string,int> mp;\n        istringstream ss1(s1);\n        string w;\n        while(ss1 >> w) \n        {\n            mp[w]++;\n        }\n        istringstream ss2(s2);\n        while(ss2 >> w)\n        {\n            mp[w]++;\n        }\n\n        vector<string>res;\n        for(auto& [word , count] : mp)\n        {\n            if(count == 1)\n            {\n                res.push_back(word);\n            }\n        }\n        return res;\n    }\n};\n```
['C++']