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
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 (count.count(word) && count[word] < 2)
        --count[word];

    return count_if(begin(count), end(count),
                    [](const auto& 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 = 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())
Back to top