Skip to content

2085. Count Common Words With One Occurrence 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countWords(vector<string>& words1, vector<string>& words2) {
    unordered_map<string, int> count;

    for (const string& word : words1)
      ++count[word];

    for (const string& word : words2)
      if (const auto it = count.find(word);
          it != count.cend() && it->second < 2)
        --it->second;

    return ranges::count_if(
        count, [](const pair<string, int>& c) { return c.second == 0; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int countWords(String[] words1, String[] words2) {
    Map<String, Integer> count = new HashMap<>();

    for (final String word : words1)
      count.merge(word, 1, Integer::sum);

    for (final String word : words2)
      if (count.containsKey(word) && count.get(word) < 2)
        count.merge(word, -1, Integer::sum);

    return (int) count.values().stream().filter(v -> v == 0).count();
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def countWords(self, words1: list[str], words2: list[str]) -> int:
    count = collections.Counter(words1)

    for word in words2:
      if word in count and count[word] < 2:
        count[word] -= 1

    return sum(value == 0 for value in count.values())