Intersection of Two Arrays (LeetCode 349): Solution and Explanation

Easy
Array
Hash Table
Two Pointers
Binary Search
Sorting

Given two integer arrays, return the values that appear in both of them. Each value in the result must be unique, and the result can be returned in any order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force takes each element of the first array and scans the second array for it, then removes duplicates from the matches. That is O(n × m) comparisons, and the duplicate handling adds bookkeeping on top. It works for the small limits here but is clearly wasteful.

Two features of the problem point straight to hash sets. First, membership tests are the core operation: for each value, you need to know whether it exists in the other array, and a set answers that in O(1) on average. Second, the result must contain each value only once, and a set naturally removes duplicates.

So convert both arrays to sets, which throws away repeats like the second 2 in [1,2,2,1], and take their intersection. In Python the & operator does exactly that, iterating over the smaller set and keeping the elements found in the other. Converting the result back to a list gives the answer. Because the values here are bounded between 0 and 1000, a boolean array of size 1001 could replace the sets entirely, which is a nice trick when the value range is small and known in advance.

If you want to save memory, you can build a set from only one array and then walk the second array, adding matches to a result set. The asymptotic cost is the same, but you avoid storing the second array's set. And if the arrays were already sorted, a two-pointer walk would find common values without any hashing at all.

Approach: Hash set intersection

  1. Build set1 from nums1, which removes its duplicates.
  2. Build set2 from nums2 the same way.
  3. Compute set1 & set2, the values present in both sets.
  4. Convert the intersection to a list and return it. The order is not specified, so any order is accepted.

Step-by-step example

nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  1. set1 becomes {4, 9, 5}.
  2. set2 becomes {9, 4, 8}, since the repeated 9 and 4 collapse into single entries.
  3. The intersection keeps 4 and 9, which appear in both sets, and drops 5 and 8.
  4. The function returns [4, 9], or [9, 4]; both are correct because order does not matter.

Code: Python, Java, C++

1class Solution:
2    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
3        set1 = set(nums1)
4        set2 = set(nums2)
5        return list(set1 & set2)

Time and space complexity

Time

O(n + m)

Building the two sets touches every element once, and the intersection does one average O(1) lookup per element of the smaller set.

Space

O(n + m)

Both sets are stored, and in the worst case each holds every element of its array. The output list can be as large as the smaller set, when every distinct value is shared.

Other approaches

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

Sort both arrays, then walk them with one pointer each, advancing the smaller value and recording a match when they are equal, skipping repeats. It needs no hash table and suits data that is already sorted.

Binary search (time O((n + m) log n), space O(n))

Sort the smaller array, then binary search it for each element of the larger one, collecting matches in a set. This is a reasonable choice when one array is much smaller than the other.

Common mistakes

  • Returning duplicates, such as [2, 2] for the first example. The result must contain each common value only once.
  • Confusing this with Intersection of Two Arrays II, which keeps duplicates as many times as they appear in both arrays and needs counts instead of sets.
  • Using nested loops with a list for the result and in checks on that list, which quietly turns an O(n × m) solution into something even slower.
  • Assuming the output must be sorted. The order is free, so sorting the result only adds cost.

Frequently asked questions

What is the time complexity of Intersection of Two Arrays?

With hash sets it is O(n + m), because each element is inserted or looked up once in constant average time. Space is also O(n + m) for the sets.

How is it different from Intersection of Two Arrays II?

The second version keeps repeated values, so [1,2,2,1] and [2,2] give [2,2]. You solve it with a frequency map or by sorting both arrays and walking them with two pointers.

Can I solve it without extra space?

Yes, if you are allowed to sort the inputs. Sort both arrays and walk them with two pointers, adding a value only when it differs from the last one added.

What if one array is much larger than the other?

Build the set from the smaller array and stream the larger one against it, so memory stays proportional to the small input. If the large array lives on disk, this is the only practical choice. You read it in chunks, test each value against the in-memory set, and add matches to a small result set, so memory never depends on the size of the large input.