Count Common Words With One Occurrence - Problem

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

A string appears exactly once in an array if it occurs exactly once and does not appear in any other position in that array.

Input & Output

Example 1 — Basic Case
$ Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
💡 Note: "leetcode" appears once in each array, "amazing" appears once in each array. "is" appears twice in words1, so it doesn't qualify.
Example 2 — No Common Single Words
$ Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
Output: 0
💡 Note: No words appear in both arrays, so the count is 0.
Example 3 — All Qualify
$ Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"]
Output: 1
💡 Note: "a" appears once in words1 but three times in words2. "ab" appears once in both arrays, so result is 1.

Constraints

  • 1 ≤ words1.length, words2.length ≤ 1000
  • 1 ≤ words1[i].length, words2[j].length ≤ 30
  • words1[i] and words2[j] consist only of lowercase English letters

Visualization

Tap to expand
Count Common Words With One Occurrencewords1 = ["leetcode","is","amazing","as","is"]words2 = ["amazing","leetcode","is"]Frequency Count:"leetcode": 1"is": 2"amazing": 1Frequency Count:"amazing": 1"leetcode": 1"is": 1Common (freq=1):✓ "leetcode"✓ "amazing"✗ "is" (freq=2 in words1)Output: 2
Understanding the Visualization
1
Input Arrays
Two string arrays with possibly duplicate words
2
Count Frequencies
Build frequency maps for both arrays
3
Find Intersection
Count words with frequency 1 in both arrays
Key Takeaway
🎯 Key Insight: Only words appearing exactly once in both arrays qualify - frequency maps make this check efficient
Asked in
Amazon 15 Microsoft 8
27.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen