Count Common Words With One Occurrence - Problem

Given two string arrays words1 and words2, your task is to find strings that are uniquely shared between both arrays.

A string counts toward our answer if and only if:

  • It appears exactly once in words1
  • It appears exactly once in words2

Return the number of such strings.

Example:

If words1 = ["leetcode", "is", "amazing", "as", "is"] and words2 = ["amazing", "leetcode", "is"]

The word "is" appears twice in words1, so it doesn't count. The words "leetcode" and "amazing" each appear exactly once in both arrays, so our answer is 2.

Input & Output

example_1.py โ€” 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 count. "as" doesn't appear in words2.
example_2.py โ€” No Common Words
$ Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
โ€บ Output: 0
๐Ÿ’ก Note: No words appear in both arrays, so the result is 0.
example_3.py โ€” All Duplicates
$ Input: words1 = ["a","ab","a"], words2 = ["a","ab","ab"]
โ€บ Output: 0
๐Ÿ’ก Note: "a" appears twice in words1, "ab" appears twice in words2. No word appears exactly once in both arrays.

Visualization

Tap to expand
๐Ÿ•ต๏ธ Word Frequency Detective๐Ÿ“‹ Report 1 (words1)"suspect" appears 1 time"car" appears 2 times"blue" appears 1 time"fast" appears 1 time๐Ÿ“‹ Report 2 (words2)"suspect" appears 1 time"blue" appears 1 time"slow" appears 1 time๐ŸŽฏ Reliable Evidenceโœ“ "suspect": mentioned once in each reportโœ“ "blue": mentioned once in each reportTotal Reliable Statements: 2Hash tables help us count frequencies efficiently in O(n+m) time
Understanding the Visualization
1
Collect Evidence
Count how many times each statement appears in each report
2
Identify Reliable Statements
Find statements mentioned exactly once in both reports
3
Count Valid Evidence
Count the reliable statements for your final report
Key Takeaway
๐ŸŽฏ Key Insight: Use frequency counting with hash tables to efficiently find words that appear exactly once in both arrays, achieving optimal O(n+m) time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n + m)

Linear scan of both arrays plus one pass through frequency map

n
2n
โœ“ Linear Growth
Space Complexity
O(n + m)

Hash maps store at most n+m unique words from both arrays

n
2n
โšก Linearithmic Space

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
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 22
24.7K Views
Medium Frequency
~15 min Avg. Time
892 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