Count Common Words With One Occurrence — LeetCode 2085 Python Solution
EasyArrayHash TableStringCounting
- Problem
- #2085
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
Example
- Input
- words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
- Output
- 2
- Explanation
- - "leetcode" appears exactly once in each of the two arrays. We count this string.
Python solution
Python
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
cnt1 = Counter(words1)
cnt2 = Counter(words2)
return sum(v == 1 and cnt2[w] == 1 for w, v in cnt1.items())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(n + m) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2085. Count Common Words With One Occurrence is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2085. Count Common Words With One Occurrence?
- LeetCode 2085. Count Common Words With One Occurrence is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2085. Count Common Words With One Occurrence?
- The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 2085. Count Common Words With One Occurrence?
- The Python solution on this page uses O(n + m) auxiliary space.
- What topics does LeetCode 2085. Count Common Words With One Occurrence cover?
- LeetCode 2085. Count Common Words With One Occurrence is tagged Array, Hash Table, String and Counting on LeetCode.