#2085

Count Common Words With One Occurrence

Easy
LeetCode ↗

Approaches

💡

Intuition

Time O(n²)Space O(1)

We can check each word in the first array against every word in the second array. This is straightforward but inefficient for larger inputs.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each word in words1, count its occurrences.
  2. 2Step 2: For each word in words2, count its occurrences.
  3. 3Step 3: Check each word from words1 against words2 to see if it appears exactly once in both.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def count_common_words(words1, words2):
5    count1 = Counter(words1)
6    count2 = Counter(words2)
7    common_count = 0
8    for word in count1:
9        if count1[word] == 1 and count2[word] == 1:
10            common_count += 1
11    return common_count
12
13# Example usage
14print(count_common_words(["leetcode","is","amazing","as","is"], ["amazing","leetcode","is"]))

Complexity note: This complexity arises because we are checking each word in words1 against every word in words2, leading to a quadratic number of checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.