Skip to content

884. Uncommon Words from Two Sentences

https://leetcode.com/problems/uncommon-words-from-two-sentences/

js
/**
 * @param {string} A
 * @param {string} B
 * @return {string[]}
 */
var uncommonFromSentences = function(A, B) {
  const counter = {}
  A.split(' ').forEach(w => {
    counter[w] = (counter[w] || 0) + 1
  })
  B.split(' ').forEach(w => {
    counter[w] = (counter[w] || 0) + 1
  })
  return Object.entries(counter).reduce((ret, [w, c]) => {
    if (c === 1) {
      ret.push(w)
    }
    return ret
  }, [])
}
py
class Solution:

    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        counter = {}
        for w in A.split() + B.split():
            counter[w] = counter.get(w, 0) + 1
        return [w for w in counter if counter[w] == 1]