Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Intersection of Two Arrays

Intersection of Two Arrays

Problem Statement

You’re a matchmaker with two arrays of integers. Your goal: find all numbers they share, returning unique values. This easy-level set challenge is a Venn diagram in code—use hashing to uncover the overlap with style!

Example

Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]

Output: [2] (Only 2 is common, unique)

Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]

Output: [4, 9] (Common and unique)

Input: nums1 = [1], nums2 = [2]

Output: [] (No intersection)

Code

Java
Python
JavaScript
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set set1 = new HashSet<>();
        for (int num : nums1) set1.add(num);
        Set result = new HashSet<>();
        for (int num : nums2) {
            if (set1.contains(num)) result.add(num);
        }
        int[] output = new int[result.size()];
        int i = 0;
        for (int num : result) output[i++] = num;
        return output;
    }
}
            
def intersection(nums1, nums2):
    return list(set(nums1) & set(nums2))  # Set intersection
            
function intersection(nums1, nums2) {
    let set1 = new Set(nums1);
    let result = new Set();
    for (let num of nums2) {
        if (set1.has(num)) result.add(num);
    }
    return Array.from(result);
}
            

Explanation

  • Set Insight: Sets ensure uniqueness and enable fast lookups.
  • Flow: Convert nums1 to a set, check nums2 against it, collect matches in another set.
  • Example Walkthrough: [1,2,2,1],[2,2] → set1={1,2}, result={2}.
  • Python Shortcut: Use & operator for set intersection—super concise!
  • Optimization: Smaller array as set1 minimizes space if one is much larger.

Note

Time complexity: O(n + m), Space complexity: O(min(n, m)). A set-driven matchmaker’s delight!