Count Common Words With One Occurrence

Here’s a way to achieve the given task by defining the countWords function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from collections import Counter

class Solution:
    def countWords(self, words1: List[str], words2: List[str]) -> int:
        # Count the occurrence of each word in words1
        count1 = Counter(words1)

        # Count the occurrence of each word in words2
        count2 = Counter(words2)

        # Initialize a variable to hold the count of words that appear exactly once in both arrays
        result = 0

        # Iterate through the count1 dictionary
        for word, count in count1.items():
            # Check if the word appears exactly once in both arrays
            if count == 1 and count2[word] == 1:
                # Increment the result by 1
                result += 1

        return result

Explanation

  • This code uses the Counter class from the collections module to count the occurrences of each word in words1 and words2.
  • It initializes a variable result to keep track of the number of strings that appear exactly once in both arrays.
  • Then, it iterates through the count of words in words1 and checks if any word appears exactly once in both words1 and words2. If so, it increments the result by 1.
  • Finally, it returns the result, which is the number of strings that appear exactly once in each of the two arrays.