Leetcode 884. Uncommon Words from Two Sentences
You are given two sentences s1
and s2
. A word is considered uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. You need to return a list of all the uncommon words.
Given these questions, let’s assume:
Here’s the implementation in C++:
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
using namespace std;
vector<string> uncommonFromSentences(string s1, string s2) {
unordered_map<string, int> word_count;
stringstream ss(s1 + " " + s2);
string word;
// Count the frequency of each word
while (ss >> word) {
word_count[word]++;
}
// Collect words that appear exactly once
vector<string> result;
for (const auto& entry : word_count) {
if (entry.second == 1) {
result.push_back(entry.first);
}
}
return result;
}
// Example usage
int main() {
string s1 = "this apple is sweet";
string s2 = "this apple is sour";
vector<string> uncommon_words = uncommonFromSentences(s1, s2);
for (const string& word : uncommon_words) {
cout << word << " ";
}
return 0;
}
s1 + s2
.Overall time complexity is: [ O(n + m) ] where n is the length of the combined sentences and m is the number of unique words.
Thus, the space complexity is: [ O(m) ]
This solution should efficiently handle the problem within the given constraints.
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?