Code Logo

Intersection of Two Arrays

Published at23 Jul 2026
Easy 2 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

Solution Approach

Find the intersection of two arrays: return elements that appear in both arrays. Use a hash set to store unique elements from the first array, then check each element of the second array against the set. Elements found in both are added to the result set to avoid duplicates.

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

Deleting from the set after finding a match prevents duplicate entries in the result. If an element appears multiple times in both arrays, it is included only once in the intersection.

Time complexity is O(n + m), space complexity is 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;
    }
}