Code Logo

Intersection of Two Arrays

Published at23 Jul 2026
Easy 0 views
Like0

Given two integer arrays, return an array of their intersection. Each element in the result must be unique. The order of the result can be arbitrary.

Use a hash set to store elements from the first array. Then iterate through the second array: if an element exists in the set, add it to the result and remove it from the set (to prevent duplicates in the result). This runs in O(n+m) time and O(n) space.

For example, nums1 = [1,2,2,1], nums2 = [2,2] → result is [2]. Only unique intersecting elements are included.

If the arrays are sorted, an alternative two-pointer approach can solve this in O(n+m) time with O(1) space. However, the hash set approach works on unsorted arrays and is simpler.

The problem can also be solved by sorting both arrays and using two pointers, which uses O(1) space but requires sorting first. The hash set approach is preferred when space is not a concern because it is simpler and works on unsorted data.

Example Input & Output

Example 1
Input
[1,2,2,1], [2,2]
Output
[2]
Explanation

Intersection is 2 (unique).

Example 2
Input
[1,2], [3,4]
Output
[]
Explanation

No common elements.

Example 3
Input
[4,9,5], [9,4,9,8,4]
Output
[9,4]
Explanation

Order does not matter.

Algorithm Flow

Recommendation Algorithm Flow for Intersection of Two Arrays
Recommendation Algorithm Flow for Intersection of Two Arrays

Solution Approach

Add all nums1 elements to a set. Iterate nums2, if element in set, add to result and remove from set.

function solution(nums1, nums2) {
  var set = {};
  for (var i = 0; i < nums1.length; i++) set[nums1[i]] = true;
  var result = [];
  for (var i = 0; i < nums2.length; i++) {
    if (set[nums2[i]]) { result.push(nums2[i]); set[nums2[i]] = false; }
  }
  return result;
}

Time O(n+m), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int[] solution(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        for (int n : nums1) set.add(n);
        List<Integer> list = new ArrayList<>();
        for (int n : nums2) {
            if (set.contains(n)) { list.add(n); set.remove(n); }
        }
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) result[i] = list.get(i);
        java.util.Arrays.sort(result);
        return result;
    }
}