Intersection of Two Arrays II
LeetCode 350 · Easy · solution, intuition & step-by-step walkthrough
Count the smaller array; consume counts while scanning the other.
This is how I solved Intersection of Two Arrays II (LeetCode 350), an easy problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Count how many times each value appears in the smaller array, then walk the other array and take a value only while its count is still positive — that keeps the multiplicity right.
Approach
- 1
Swap so nums1 is the smaller array (keeps the map small).
- 2
Build a frequency map of nums1.
- 3
For each value in nums2 with a positive count, append it and decrement.
How I solved it
Hash map countsPythonO(n+m) time · O(min) space
class Solution:
def intersect(self, nums1: list[int], nums2: list[int]) -> list[int]:
n = len(nums1)
m = len(nums2)
res = []
if n>m:
return self.intersect(nums2,nums1)
freq_map = defaultdict(int)
for num in nums1:
freq_map[num]+=1
for num in nums2:
if freq_map[num]>=1:
freq_map[num]-=1
res.append(num)
return resIntersection of Two Arrays II — FAQ
What is the intuition behind Intersection of Two Arrays II?
Count how many times each value appears in the smaller array, then walk the other array and take a value only while its count is still positive — that keeps the multiplicity right.
How do you solve Intersection of Two Arrays II (LeetCode 350)?
1. Swap so nums1 is the smaller array (keeps the map small). 2. Build a frequency map of nums1. 3. For each value in nums2 with a positive count, append it and decrement.
What is the time and space complexity of Intersection of Two Arrays II?
Time: O(n + m). Space: O(min(n, m)). (Accepted approach: Hash map counts.)
What are common mistakes in Intersection of Two Arrays II?
Decrement the count so a value isn't used more times than it appears in both.