Intersection of Two Arrays

Easyarrayhash-tabletwo-pointersbinary-search
Category: Array & Hashing
Companies that ask this question:
AmazonFacebookGoogle

Approach

Intersection of Two Arrays

Problem Statement

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Examples

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]

Approach

Use two hash sets: one for nums1, check nums2 against it, collect results in another set.

Complexity

  • Time: O(m + n)
  • Space: O(m + n)

Solution

java
1class Solution {
2    public int[] intersection(int[] nums1, int[] nums2) {
3        Set<Integer> set1 = new HashSet<>();
4        Set<Integer> result = new HashSet<>();
5        
6        for (int num : nums1) set1.add(num);
7        for (int num : nums2) {
8            if (set1.contains(num)) result.add(num);
9        }
10        
11        return result.stream().mapToInt(Integer::intValue).toArray();
12    }
13}
Loading visualizer...