Skip to content

Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear only once, and the result can be in any order.

nums1nums2OutputExplanation
[1, 2, 2, 1][2, 2][2]2 is common; duplicates collapsed
[4, 9, 5][9, 4, 9, 8, 4][9, 4]9 and 4 are common
  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000
ApproachTimeSpaceBest When
Hash SetO(n + m)O(min(n, m))Unsorted arrays; fast lookup
Two PointersO(n log n + m log m)O(1)*Arrays are already sorted or memory is scarce

* O(1) extra space beyond the output array (sort is in-place).

  • Learn Hash Set first — it is the faster approach for unsorted inputs and the standard expectation in interviews.
  • Learn Two Pointers as a follow-up — it demonstrates the general sorted-merge pattern used across many problems.
Best For Speed
Hash Set
O(n+m) time · O(min(n,m)) space
No Extra Memory
Two Pointers
O(n log n + m log m) time · O(1) space
★ Recommended

Convert nums1 into a set to deduplicate it. Scan nums2 and collect every element that is in the set into a result set (to prevent duplicates in the output). Convert the result set to a list.

⏱ Time O(n + m) One pass each 💾 Space O(min(n, m)) Set of the smaller array

Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]

PhaseActionResult set
Build set from nums1{4, 9, 5}
Check 9 from nums29 ∈ set1{9}
Check 4 from nums24 ∈ set1{9, 4}
Check 9 againAlready in result{9, 4}
Check 88 ∉ set1{9, 4}
Check 4 againAlready in result{9, 4}
Return[9, 4]

Animated walkthrough

How the hash set finds the unique intersection

Use Next or Autoplay to see nums1 converted to a lookup set, then nums2 scanned for matches.

Step 1 of 4
Waiting to begin...
Array state
Memory / lookup state

function intersection(nums1, nums2):
set1 = set(nums1)
result = set()
for num in nums2:
if num in set1:
result.add(num)
return list(result)
intersection_of_two_arrays_hash_set.py
from typing import List
def intersection(nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
🎯 Interview Favourite

Sort both arrays. Use two pointers starting at the beginning of each. Advance the pointer pointing to the smaller value. When both pointers point to equal values, record the result (skipping consecutive duplicates) and advance both.

⏱ Time O(n log n + m log m) Sort dominates 💾 Space O(1) In-place sort, no extra structure

Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]

After sorting: nums1 = [4, 5, 9], nums2 = [4, 4, 8, 9, 9]

ijnums1[i]nums2[j]Actionresult
0044Equal → add, both++[4]
12585 < 8 → i++[4]
22989 > 8 → j++[4]
2399Equal → add, both++[4, 9]
35Done[4, 9]
function intersection(nums1, nums2):
sort(nums1); sort(nums2)
result = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
if not result or result[-1] != nums1[i]:
result.append(nums1[i])
i++; j++
elif nums1[i] < nums2[j]:
i++
else:
j++
return result
intersection_of_two_arrays_two_pointer.py
from typing import List
def intersection(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]:
if not result or result[-1] != nums1[i]:
result.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return result
print(intersection([4, 9, 5], [9, 4, 9, 8, 4])) # [4, 9]
print(intersection([1, 2, 2, 1], [2, 2])) # [2]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
intersection_of_two_arrays_optimized.py
"""
Solution for Intersection of Two Arrays
"""
def solve():
"""Implementation for approach 3 of Intersection of Two Arrays"""
pass
if __name__ == "__main__":
print("Solution ready")