Intersection of Two Arrays II (LeetCode 350): Solution and Explanation

Easy
Array
Hash Table
Two Pointers
Binary Search
Sorting

Given two integer arrays, return their intersection where each value appears as many times as it shows up in both arrays. The result can be in any order.

Intuition

Unlike the first version of this problem, duplicates matter. If 7 appears twice in nums1 and three times in nums2, the answer holds two 7s, because only two pairs can be formed. In general each value appears min(count in nums1, count in nums2) times.

Think of nums1 as a supply and nums2 as a list of requests. Count how many copies of each value nums1 supplies. Then walk nums2: a request for x is granted when a copy of x is still available, and each grant uses one copy up.

Once a value's count reaches zero, later requests for it are skipped even though the value is in nums1. That is how the result stops at the smaller of the two counts.

Approach: Count, then claim

  1. Build counts mapping each value of nums1 to how many times it appears.
  2. Start an empty res.
  3. For each x in nums2, if counts.get(x, 0) > 0, append x to res and decrement counts[x].
  4. Return res.

Step-by-step example

nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  1. Count nums1: {4: 1, 9: 1, 5: 1}.
  2. x = 9: counts[9] is 1, take it. res = [9], counts[9] = 0.
  3. x = 4: counts[4] is 1, take it. res = [9,4], counts[4] = 0.
  4. x = 9: counts[9] is 0, every 9 from nums1 is used, skip.
  5. x = 8: nums1 never had 8, skip.
  6. x = 4: counts[4] is 0, skip. Return [9,4], which matches [4,9] since order does not matter.

Code: Python, Java, C++

1class Solution:
2    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
3        counts = {}
4        for x in nums1:
5            counts[x] = counts.get(x, 0) + 1
6        res = []
7        for x in nums2:
8            if counts.get(x, 0) > 0:
9                res.append(x)
10                counts[x] -= 1
11        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

One pass over nums1 to count and one pass over nums2 to claim, each with constant time map operations.

Space

O(n)

The count map holds at most the distinct values of nums1. Counting the smaller array keeps it at O(min(n, m)).

Other approaches

Sort and two pointers (time O(n log n + m log m), space O(1) beyond sorting)

Sort both arrays and walk them together. Advance the pointer at the smaller value; on equal values, record it and advance both. This is the natural answer to the follow up where the arrays are already sorted.

Counter intersection (time O(n + m), space O(n + m))

In Python, (Counter(nums1) & Counter(nums2)).elements() takes the minimum count per key directly. It is short, but it builds two maps instead of one.

Common mistakes

  • Using sets as in Intersection of Two Arrays. Sets drop duplicates, so [1,2,2,1] and [2,2] would return [2] instead of [2,2].
  • Forgetting to decrement after a match. Then every request for a value present in nums1 is granted, and nums2 = [2,2,2] against nums1 = [2] returns three 2s.
  • Removing elements from a list with list.remove to mark them used. That is O(n) per removal and turns the solution quadratic.

Frequently asked questions

How many times should a value appear in the result?

Exactly min(count in nums1, count in nums2) times. The count map enforces this because each copy from nums1 can be claimed only once.

What if nums2 is too large to fit in memory?

Count the array that does fit (nums1) and stream nums2 in chunks, claiming copies as you go. If both are too large, sort them externally and merge with two pointers.

What is the time and space complexity of Intersection of Two Arrays II?

O(n + m) time with the count map, and O(min(n, m)) space when you count the smaller array.