Intersection of Two Arrays II
easyTime: O(m + n)Space: O(min(m, n))
Signals to notice
find common elementstwo sorted arraysfrequency matching
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.
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.
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.