algoadvance

You are given two string arrays words1 and words2. A word is common if it appears in both arrays. A common word is considered to have “one occurrence” if it appears exactly once in each of the given arrays.

Your task is to return the number of common words with one occurrence.

Clarifying Questions

  1. Input Constraints:
    • What is the length range of words1 and words2? (0 ≤ len(words1), len(words2) ≤ 1000)
    • What’s the length range for the words within the arrays? (1 ≤ len(word) ≤ 30)
    • Will the strings only contain lowercase English letters? (Yes)
  2. Output:
    • We need to return an integer representing the count of common words with one occurrence.
  3. Examples:
    • Example 1:
      • Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
      • Output: 2
    • Example 2:
      • Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
      • Output: 0

Code

Here’s the Python code to solve the problem:

from collections import Counter

def countWords(words1, words2):
    # Count the frequency of each word in both lists
    count1 = Counter(words1)
    count2 = Counter(words2)
    
    # Initialize count of common words with exactly one occurrence
    common_one_occurrence = 0
    
    # Iterate through the words in count1
    for word in count1:
        # Check if the word has exactly one occurrence in both count1 and count2
        if count1[word] == 1 and count2[word] == 1:
            common_one_occurrence += 1
    
    return common_one_occurrence

# Example Usage
words1 = ["leetcode","is","amazing","as","is"]
words2 = ["amazing","leetcode","is"]
print(countWords(words1, words2))  # Output: 2

Strategy

  1. Count Frequencies:
    • Utilize the Counter class from the collections module to count how many times each word appears in both words1 and words2.
  2. Identify Common Words with One Occurrence:
    • Iterate over the keys (words) of one of the Counters (count1).
    • For each word, check if it appears exactly once in both count1 and count2.
  3. Increment the Count:
    • Keep a count of how many words meet the criteria and return this count.

Time Complexity

Overall, the solution has a time complexity of O(n + m) where n and m are the lengths of words1 and words2, respectively. This is efficient given the input constraints.

Try our interview co-pilot at AlgoAdvance.com