LeetCodee

349. Intersection of Two Arrays

Jump to Solution: Python Java C++ JavaScript C#

Problem Description

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.

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]
Explanation: [4,9] is also accepted.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Solution

Python Solution

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Convert arrays to sets for O(1) lookup
        set1 = set(nums1)
        set2 = set(nums2)
        
        # Return intersection of sets
        return list(set1 & set2)

Time Complexity: O(n + m)

Where n and m are the lengths of the input arrays.

Space Complexity: O(min(n, m))

For storing the intersection set.

Java Solution

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // Convert first array to set for O(1) lookup
        Set set = new HashSet<>();
        for (int num : nums1) {
            set.add(num);
        }
        
        // Find intersection
        Set intersection = new HashSet<>();
        for (int num : nums2) {
            if (set.contains(num)) {
                intersection.add(num);
            }
        }
        
        // Convert set to array
        int[] result = new int[intersection.size()];
        int i = 0;
        for (int num : intersection) {
            result[i++] = num;
        }
        
        return result;
    }
}

Time Complexity: O(n + m)

Where n and m are the lengths of the input arrays.

Space Complexity: O(min(n, m))

For storing the sets.

C++ Solution

class Solution {
public:
    vector intersection(vector& nums1, vector& nums2) {
        // Convert first array to set for O(1) lookup
        unordered_set set(nums1.begin(), nums1.end());
        
        // Find intersection
        unordered_set intersection;
        for (int num : nums2) {
            if (set.count(num)) {
                intersection.insert(num);
            }
        }
        
        // Convert set to vector
        return vector(intersection.begin(), intersection.end());
    }
};

Time Complexity: O(n + m)

Where n and m are the lengths of the input arrays.

Space Complexity: O(min(n, m))

For storing the sets.

JavaScript Solution

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
    // Convert arrays to sets for O(1) lookup
    const set1 = new Set(nums1);
    const set2 = new Set(nums2);
    
    // Find intersection
    const result = [];
    for (const num of set1) {
        if (set2.has(num)) {
            result.push(num);
        }
    }
    
    return result;
};

Time Complexity: O(n + m)

Where n and m are the lengths of the input arrays.

Space Complexity: O(min(n, m))

For storing the sets.

C# Solution

public class Solution {
    public int[] Intersection(int[] nums1, int[] nums2) {
        // Convert first array to set for O(1) lookup
        HashSet set = new HashSet(nums1);
        
        // Find intersection
        HashSet intersection = new HashSet();
        foreach (int num in nums2) {
            if (set.Contains(num)) {
                intersection.Add(num);
            }
        }
        
        return intersection.ToArray();
    }
}

Time Complexity: O(n + m)

Where n and m are the lengths of the input arrays.

Space Complexity: O(min(n, m))

For storing the sets.

Approach Explanation

The solution uses hash sets for efficient lookup:

  1. Key Insight:
    • Set operations
    • O(1) lookup
    • Unique elements
    • Order irrelevant
  2. Algorithm Steps:
    • Create sets
    • Find common
    • Convert result
    • Handle duplicates

Example walkthrough:

  • Convert to sets
  • Check membership
  • Build result
  • Return array

Optimization insights:

  • Hash set usage
  • Single pass
  • Memory efficient
  • Built-in methods

Edge Cases:

  • Empty arrays
  • No intersection
  • All same elements
  • Different sizes