Uncommon Words from Two Sentences

easy hash map string counting

Problem

A sentence is a string of single-space separated words. 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.

Inputs1 = "this apple is sweet", s2 = "this apple is sour"
Output["sweet", "sour"]
Across both sentences combined, "sweet" and "sour" each occur exactly once; "this", "apple", "is" each occur twice.

def uncommon_from_sentences(s1, s2):
    count = {}
    for w in (s1 + " " + s2).split():
        count[w] = count.get(w, 0) + 1
    return [w for w, c in count.items() if c == 1]
function uncommonFromSentences(s1, s2) {
  const count = new Map();
  for (const w of (s1 + " " + s2).split(/\s+/)) {
    count.set(w, (count.get(w) || 0) + 1);
  }
  const res = [];
  for (const [w, c] of count) if (c === 1) res.push(w);
  return res;
}
class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        Map<String, Integer> count = new HashMap<>();
        for (String w : (s1 + " " + s2).split(" ")) {
            count.merge(w, 1, Integer::sum);
        }
        List<String> res = new ArrayList<>();
        for (Map.Entry<String, Integer> e : count.entrySet())
            if (e.getValue() == 1) res.add(e.getKey());
        return res.toArray(new String[0]);
    }
}
vector<string> uncommonFromSentences(string s1, string s2) {
    unordered_map<string, int> count;
    istringstream in(s1 + " " + s2);
    string w;
    while (in >> w) count[w]++;
    vector<string> res;
    for (auto& p : count) if (p.second == 1) res.push_back(p.first);
    return res;
}
Time: O(m + n) Space: O(m + n)