15% off all plans & roadmaps Use code
See plansIntersection of Two Arrays
- LeetCode 349
- Easy
- Two Pointers
- In-place Array Modification
Updated
TL;DR: You get two integer arrays and must return the values that appear in both, each listed once. A hash set built from one array answers each membership check in expected constant time, which removes the nested scan.
Problem
You receive two integer arrays, nums1 and nums2. Return an array that holds the values present in both. Each value must appear only once in the result, and the result may come back in any order.
Example 1
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also an accepted answer.
Constraints
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000
Constraints that matter
- Values stay between 0 and 1000, so a fixed table of 1001 slots covers every possible value. That makes a boolean lookup table a valid option.
- Lengths reach 1000, so a nested loop does up to about 10^6 comparisons. That fits the limits, but interviewers expect you to name the cost and improve on it.
- Each array can hold repeated values, so the output step must check for duplicates. Without that check, the answer can list the same value more than once.
- The output order is free. You never need to keep positions or match indices, which frees you to use a set.
Hints
Hint 1
This problem asks a membership question.
Hint 2
Compare every value in nums1 with every value in nums2.
Solution
Intuition
This problem asks a membership question. For each value in one array, you need to know whether the other array contains it. A hash set is built for that job, so the pattern is hash set membership. Sorting and two pointers also solve it, and you will see that route as the second approach.
Picture a bouncer with a guest list. The hash set is the guest list built from nums1, and each value in nums2 is a person at the door who gets checked once.
Two phrases in the statement point the way. Values that appear in both arrays means you test membership across arrays. Each value appears once in the result means you need a set for the output, or a check against the last value you wrote. Because the order is free, you never track positions.
Sorting helps for a different reason. Equal values end up next to each other once both arrays are sorted. A pair of pointers can then walk both arrays in step, moving forward and never backtracking. The hash set skips the sort entirely and answers each lookup from a table, trading some extra memory for a single pass over the second array.
Worked example
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Explanation: The value 2 appears in both arrays, and 1 appears only in nums1. The result lists 2 once even though nums1 holds two copies of it and nums2 holds two copies too.
Approach 1: Brute force
Compare every value in nums1 with every value in nums2. When a pair matches, add the value to the answer unless it is already there. This is the direct reading of the statement, and it fits the limits. Each value in nums1 can force a full scan of nums2, so the work grows with the product of the two lengths.
Steps
- Create an empty list named result.
- For each x in nums1, scan every y in nums2.
- When x equals y, check whether x is already in result.
- If x is missing from result, append it.
- Stop scanning nums2 for this x, because one match is enough.
- Return result.
Dry run
Start with x = 1. The inner scan finds no 1 in [2, 2], so nothing is added.
Next, x = 2. The scan matches at y = 2, and result is empty, so result becomes [2].
Next, x = 2 again. The scan matches, but 2 is already in result, so nothing changes.
Last, x = 1. The scan finds no match. The output is [2].
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(min(n, m)) |
Let n be the length of nums1 and m the length of nums2. For each of the n values in nums1, the inner loop reads up to m values from nums2, which gives O(n * m) comparisons. The membership check on result runs at most once per x and costs at most the size of result, which never exceeds m, so it stays within the same bound. The result holds only distinct values taken from both arrays, so it never grows past min(n, m) entries.
PythonTested in our runner
from typing import List, Optional
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
result = []
for x in nums1:
for y in nums2:
if x == y:
# append only the first time this value appears
if x not in result:
result.append(x)
break
return resultThe In-place Array Modification infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
In-place Array Modification
Part of Two Pointers
Approach 2: Sort, then two pointersIn-place Array Modification
What is slow in the brute force: it rescans nums2 for every value in nums1, and most of those scans cannot produce a match. The insight that fixes it is order. Once both arrays are sorted, a smaller value in one array cannot match anything the other pointer has passed. So you advance whichever pointer holds the smaller value, and you only compare each pair of positions once. Equal values also sit next to each other, so a repeat only needs a check against the last value written.
Steps
- Sort nums1 in ascending order.
- Sort nums2 in ascending order.
- Set i and j to 0 and create an empty result.
- While both pointers are inside their arrays, compare nums1[i] with nums2[j].
- If nums1[i] is smaller, increment i. If nums2[j] is smaller, increment j.
- If they are equal, append the value when result is empty or its last value differs. Then increment both pointers.
- Return result.
Dry run
After sorting, nums1 is [1, 1, 2, 2] and nums2 is [2, 2].
With i = 0 and j = 0, the values are 1 and 2. The value 1 is smaller, so i moves to 1. Then nums1[1] is 1 and it is still smaller, so i moves to 2.
Now nums1[2] is 2 and nums2[0] is 2. They match. result is empty, so 2 is appended. Both pointers move: i = 3 and j = 1.
Now nums1[3] is 2 and nums2[1] is 2. They match again, but the last value in result is 2, so nothing is appended. i moves to 4 and the loop ends. The output is [2].
Complexity
| Time | O(n log n + m log m) |
|---|---|
| Space | O(log n + log m) auxiliary for an in-place sort, O(n + m) in Python, plus the result |
Let n and m be the lengths of nums1 and nums2. Sorting each array takes O(n log n) and O(m log m) comparisons with a comparison sort. The two-pointer loop advances i or j on every step, so it runs at most n + m times with O(1) work each, which gives O(n + m). The total is O(n log n + m log m), and sorting dominates. Auxiliary space depends on the sort, and the result holds at most min(n, m) distinct values.
PythonTested in our runner
from typing import List, Optional
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
result = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
# equal values are adjacent, so the last result is enough to detect repeats
if not result or result[-1] != nums1[i]:
result.append(nums1[i])
i += 1
j += 1
return resultApproach 3: One-pass hash setOptimal
What is slow in the sorted version: it pays O(n log n) to sort both arrays, yet the question only asks which values appear in both. Sorting gives more order than you need. The insight that fixes it is that membership is what matters. Put every value of nums1 into a hash set. Then scan nums2 once, and each value gets a constant-time lookup. A second set collects the matches, so each value enters the answer only once.
Steps
- Build a set named seen from every value in nums1.
- Create an empty set named result.
- Scan nums2. For each y, check whether y is in seen.
- If it is, add y to result. Adding a value that is already present changes nothing.
- Convert result to the return type, a list or array, and return it.
Dry run
Use nums1 = [1, 2, 2, 1] and nums2 = [2, 2].
| Step | Action | seen | result |
|---|---|---|---|
| 0 | build seen from nums1 | {1, 2} | {} |
| 1 | y = 2 is in seen, add it | {1, 2} | {2} |
| 2 | y = 2 is in seen, add again (no change) | {1, 2} | {2} |
| 3 | convert result to a list | {1, 2} | {2}, output [2] |
Complexity
| Time | O(n + m) |
|---|---|
| Space | O(n + m) |
Let n and m be the lengths of nums1 and nums2. Building seen inserts n values, and each insert takes expected O(1) time. The scan of nums2 does m lookups and at most m inserts, each also expected O(1). That gives O(n + m) in total. The set seen holds at most n values and result holds at most min(n, m), so the extra space is O(n + m). The O(1) cost is an average over a good hash function, not a worst case for every adversarial input.
PythonTested in our runner
from typing import List, Optional
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
seen = set(nums1)
result = set()
for y in nums2:
if y in seen:
result.add(y)
return list(result)Common mistakes
- Appending on every match in the brute force, as in
result.append(x)with no membership check. On the example this returns[2, 2], because the list has no uniqueness rule. Check the result before appending. - Calling
nums1.sort()in JavaScript without a numeric comparator. The default sort compares strings, so 10 lands before 9 and the two pointers skip real matches. Use(a, b) => a - b. - Checking
result[-1] != nums1[i]before confirming that result is non-empty. The first match then reads an empty list, which raises IndexError in Python. Testnot resultfirst. - Running the last-value duplicate check on unsorted input. The check only works because equal values sit next to each other after sorting. Without the sort, a repeated value can slip into the output.
- Looping over nums1 with
if x in seenand appending to a list. On the example this returns[2, 2], because the scan revisits each copy of 2. Add to a set instead, or check membership of the output first. - Returning the Python set
resultwhere the statement expects a list. The runner compares the type, so convert withlist(result)before returning.
Edge cases
- Single matching value, such as [5] and [5]. The answer is [5].
- No overlap, such as [1, 2] and [3]. The answer is an empty list.
- Repeated values in both arrays, such as [7, 7, 7] and [7, 7]. The answer is [7], listed once.
- Values at the bounds, such as [0, 1000] and [1000, 0]. Zero is a real value, so a sentinel of 0 for empty slots gives wrong answers. The answer contains 0 and 1000 in some order.
- Shorter array fully contained in the longer one, such as [4, 9, 5] and [9, 4, 9, 8, 4]. The answer is [4, 9] in any order.
- Maximum length on both sides, with distinct values in nums1 and nums2 drawn from 0 to 1000. Each lookup stays cheap, and the result size stays at most min(n, m).
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Intersection of Two Arrays, with how to answer them.
Unlock the follow-upsIntersection of Two Arrays FAQ
What is the time complexity of Intersection of Two Arrays?
The hash set solution runs in O(n + m) average time, where n and m are the lengths of the two arrays. The sort and two-pointer solution takes O(n log n + m log m), and the brute force takes O(n * m).
Why use a hash set for Intersection of Two Arrays?
The core question is membership, and a hash set answers each membership test in expected O(1) time. Storing the matches in a set also removes duplicates without extra checks.
Can Intersection of Two Arrays be solved in O(1) extra space?
Only with a bound on the values. Here the values lie between 0 and 1000, so a fixed boolean table works. For arbitrary integers, no fixed table works, and an in-place sort still uses O(log n) stack space in typical implementations.
Does Intersection of Two Arrays need the output sorted?
No. The statement allows any order. The two-pointer version happens to return ascending values, and the hash set version returns values in an arbitrary order.
Why does sorting in JavaScript break the two-pointer solution for Intersection of Two Arrays?
The default sort compares values as strings, so 10 comes before 9. Pass a numeric comparator such as (a, b) => a - b before running the two pointers.
Asked at
See which companies ask this — Pro
Related problems
- Contains Duplicate · same technique: In-place Array Modification
- Happy Number · same technique: In-place Array Modification
- Linked List Cycle · same technique: In-place Array Modification
- Remove Duplicates from Sorted Array · same technique: In-place Array Modification
- Remove Element · same technique: In-place Array Modification
- Contains Duplicate II · same technique: In-place Array Modification
- Sort Colors · next harder, same pattern
- Two Sum · same pattern: Two Pointers
- Valid Anagram · same pattern: Two Pointers
- Plus One · same pattern: Two Pointers