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 Occurrence INPUT words1 = "leetcode" "is" "amazing" "as" "is" words2 = "amazing" "leetcode" "is" Hash Map 1 (count): leetcode: 1 is: 2 amazing: 1 as: 1 Hash Map 2: amazing: 1 leetcode: 1 is: 1 Red = count > 1 (excluded) Blue = count = 1 (valid) ALGORITHM STEPS 1 Build Hash Map 1 Count each word in words1 2 Build Hash Map 2 Count each word in words2 3 Find Common Words Check count=1 in both maps 4 Count Valid Words Return total count Comparison Check Word Map1 Map2 OK? leetcode 1 1 OK is 2 1 NO amazing 1 1 OK as 1 - NO FINAL RESULT Valid Common Words: "leetcode" count=1 in both arrays "amazing" count=1 in both arrays Excluded Words: "is" count=2 in w1 "as" not in w2 OUTPUT 2 Two words appear exactly once in each array Key Insight: Use two hash maps to count word occurrences in each array. A word is valid only if it appears exactly once in BOTH arrays. Time: O(n + m), Space: O(n + m) where n, m are array lengths. Hash maps enable O(1) lookup to efficiently check both conditions for each word. TutorialsPoint - Count Common Words With One Occurrence | Hash Approach
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