Problem

Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

Examples

Example 1:

Input: words1 = [“leetcode”,“is”,“amazing”,“as”,“is”], words2 = [“amazing”,“leetcode”,“is”]
Output: 2
Explanation:

  • “leetcode” appears exactly once in each of the two arrays. We count this string.
  • “amazing” appears exactly once in each of the two arrays. We count this string.
  • “is” appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
  • “as” appears once in words1, but does not appear in words2. We do not count this string. Thus, there are 2 strings that appear exactly once in each of the two arrays.

Example 2:

Input: words1 = [“b”,“bb”,“bbb”], words2 = [“a”,“aa”,“aaa”]
Output: 0
Explanation: There are no strings that appear in each of the two arrays.

Example 3:

Input: words1 = [“a”,“ab”], words2 = [“a”,“a”,“a”,“ab”]
Output: 1
Explanation: The only string that appears exactly once in each of the two arrays is “ab”.

Solutions

Use two hash maps to store the frequency of each word in the two arrays and loop through them and find the ones who have frequency of 1 in both hash maps.

class Solution:
    def countWords(self, words1: List[str], words2: List[str]) -> int:
        freq1 = {}
        freq2 = {}
 
        for word in words1:
            if word in freq1:
                freq1[word] += 1
            else:
                freq1[word] = 1
 
        for word in words2:
            if word in freq2:
                freq2[word] += 1
            else:
                freq2[word] = 1
 
        count = 0
        for word in freq1:
            if word in freq2 and freq1[word] == 1 and freq2[word] == 1:
                count += 1
        
        return count
            

Or,

Use two hash sets, one for keep track of the words that only appear once and the other one to prevent duplicates. This solution uses one less for loop, but at the same time, I feel it’s less readable and less intuitive than the first.

class Solution:
    def countWords(self, words1: List[str], words2: List[str]) -> int:
        seen = set()
        freq = set()
 
        for word in words1:
            if word in freq:
                seen.add(word)
                freq.remove(word)
            elif word not in seen:
                freq.add(word)
            seen.add(word)
        
        seen = set()
        count = 0
 
        for word in words2:
            if word not in freq:
                if word in seen:
                    seen.remove(word)
                    count -= 1 
                continue
 
            count += 1
            seen.add(word)
            freq.remove(word)
            
        return count