Intersection of Two Arrays

Easy Hash SetArray

Problem

Given two integer arrays, return their intersection — each element appears once, output may be 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]

Constraints

Approach — Hashing & Counting

This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def intersection(self, nums1, nums2):
        return sorted(set(nums1) & set(nums2))

Java

import java.util.*;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> a = new TreeSet<>();
        for (int n : nums1) a.add(n);
        Set<Integer> out = new TreeSet<>();
        for (int n : nums2) if (a.contains(n)) out.add(n);
        int[] r = new int[out.size()];
        int i = 0; for (int n : out) r[i++] = n;
        return r;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Intersection of Two Arrays interactively → ← All solutions