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
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
โ Linear Growth
Space Complexity
O(n + m)
Hash maps store at most n+m unique words from both arrays
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code