Problem Statement
Intersection of Two Arrays II
You are given two lists of whole numbers, nums1 and nums2. Return a list of the numbers they share. Here is the key part: if a number shows up twice in both lists, it should show up twice in your answer. So each number appears as many times as it appears in both lists at once, which is the smaller of its two counts.
Signals to notice
Brute force first
For each element in array1, search array2. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Use a hash map to count frequencies in one array, then check against the other. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on nums1=[1,2,2,1], nums2=[2,2]
Build count1 = {1:2, 2:2} from nums1
Build count2 = {2:2} from nums2
result = []
num=1, cnt=2: 1 not in count2 -> skip; result=[]
num=2, cnt=2: 2 in count2, min(2, count2[2]=2)=2 -> extend by [2,2]; result=[2,2]
loop done -> return result=[2,2]What must stay true
The count map tracks remaining available matches; decrement on each match. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
count1 = frequency map of nums1
count2 = frequency map of nums2
result = []
for (num, cnt) in count1:
if num in count2:
append num, min(cnt, count2[num]) times
return resultPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not handling duplicate matches — decrement the count after each match to avoid reusing. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.