Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

349. Intersection of Two Arrays - Leetcode Solution

Code Implementation

class Solution:
    def intersection(self, nums1, nums2):
        set1 = set(nums1)
        set2 = set(nums2)
        return list(set1 & set2)
      
#include <vector>
#include <unordered_set>
using namespace std;

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> set1(nums1.begin(), nums1.end());
        unordered_set<int> result;
        for (int num : nums2) {
            if (set1.count(num)) {
                result.insert(num);
            }
        }
        return vector<int>(result.begin(), result.end());
    }
};
      
import java.util.*;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        for (int num : nums1) set1.add(num);
        Set<Integer> result = new HashSet<>();
        for (int num : nums2) {
            if (set1.contains(num)) result.add(num);
        }
        int[] resArr = new int[result.size()];
        int i = 0;
        for (int num : result) resArr[i++] = num;
        return resArr;
    }
}
      
var intersection = function(nums1, nums2) {
    const set1 = new Set(nums1);
    const result = new Set();
    for (let num of nums2) {
        if (set1.has(num)) {
            result.add(num);
        }
    }
    return Array.from(result);
};
      

Problem Description

You are given two arrays of integers, nums1 and nums2. The task is to return an array containing the unique elements that appear in both nums1 and nums2. Each element in the result must be unique, and the result can be returned in any order.
Key constraints:

  • Each element in the result should appear only once (no duplicates).
  • You should not reuse elements from the same array to form the intersection.
  • There is always at least one valid solution.
For example, if nums1 = [1,2,2,1] and nums2 = [2,2], then the intersection is [2].

Thought Process

At first glance, you might think to compare every element in nums1 with every element in nums2 to find matches. This brute-force approach works but is inefficient for large arrays.
To optimize, we realize that we only care about unique values and whether they exist in both arrays. Sets are perfect for this because they automatically handle uniqueness and provide fast lookup.
The idea is: if we can quickly check if a value from one array exists in the other, we can efficiently build the intersection. This leads us to consider using hash sets (or similar structures) to store the elements and perform quick membership checks.

Solution Approach

We'll use sets to solve this problem efficiently. Here are the steps:

  1. Convert both arrays to sets:
    • This removes duplicates and allows for fast lookups.
  2. Find the intersection of the two sets:
    • In most languages, sets have a built-in way to compute intersection, or you can iterate through one set and check if each element exists in the other.
  3. Return the result as a list or array:
    • The intersection set contains all unique elements present in both arrays. Convert it back to a list or array as required by the problem statement.

We use sets because:

  • They ensure each value is unique (no duplicates in the result).
  • Checking if an item exists in a set is very fast (typically O(1) time).

Example Walkthrough

Let's use the example nums1 = [4,9,5], nums2 = [9,4,9,8,4].

  1. Convert both arrays to sets:
    • set1 = {4, 9, 5}
    • set2 = {4, 8, 9}
  2. Find the intersection:
    • Which numbers are in both set1 and set2? 4 and 9.
  3. Return as a list or array:
    • The answer is [9, 4] or [4, 9] (order does not matter).

Step-by-step, we see that converting to sets filters out duplicates and allows us to efficiently find which elements are shared.

Time and Space Complexity

Brute-force approach:

  • Compare each element of nums1 with each element of nums2.
  • Time complexity: O(M*N), where M and N are the lengths of the two arrays.
  • Space complexity: O(K), where K is the size of the result set.
Optimized set-based approach:
  • Converting each array to a set: O(M + N)
  • Finding the intersection: O(min(M, N)), since we iterate over the shorter set.
  • Total time complexity: O(M + N)
  • Space complexity: O(M + N), due to the extra sets created.

The optimized approach is much faster, especially for large arrays, because set operations are highly efficient.

Summary

The key insight for this problem is to use sets to handle uniqueness and enable fast lookups. By converting both arrays to sets and finding their intersection, we solve the problem efficiently and elegantly. This approach avoids unnecessary comparisons and leverages data structures designed for exactly this kind of task.
In summary: use sets for uniqueness and speed, and simply return their intersection as the result.