HomeLeetcode349. Intersection of Two Arrays - Leetcode Solutions

349. Intersection of Two Arrays – Leetcode Solutions

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.

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

Solution in Python:

Python
from typing import List

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Convert the first list to a set to remove duplicates and allow O(1) average-time complexity checks
        set1 = set(nums1)
        
        # Initialize an empty set to store the intersection
        intersection_set = set()
        
        # Iterate through the second list
        for num in nums2:
            # If the number is in the first set, add it to the intersection set
            if num in set1:
                intersection_set.add(num)
        
        # Convert the set back to a list for the result
        return list(intersection_set)

# Example usage:
solution = Solution()
print(solution.intersection([1, 2, 2, 1], [2, 2])) # Output: [2]
print(solution.intersection([4, 9, 5], [9, 4, 9, 8, 4])) # Output: [9, 4]

Explanation:

  1. Convert to Set: Convert nums1 to a set (set1). This removes duplicates from nums1 and allows for O(1) average-time complexity checks for membership.
  2. Initialize Intersection Set: Create an empty set intersection_set to store the unique elements that are present in both nums1 and nums2.
  3. Iterate Through nums2: Loop through each element in nums2.
    • If an element from nums2 is found in set1, add it to intersection_set.
  4. Convert to List: Finally, convert the intersection_set back to a list to match the required return type.

Solution in Javascript:

JavaScript
var intersection = function(nums1, nums2) {
    // Convert the first array to a Set to remove duplicates and allow O(1) average-time complexity checks
    let set1 = new Set(nums1);
    
    // Initialize an empty Set to store the intersection
    let intersectionSet = new Set();
    
    // Iterate through the second array
    for (let num of nums2) {
        // If the number is in the first set, add it to the intersection set
        if (set1.has(num)) {
            intersectionSet.add(num);
        }
    }
    
    // Convert the set back to an array for the result
    return Array.from(intersectionSet);
};

// Example usage:
console.log(intersection([1, 2, 2, 1], [2, 2])); // Output: [2]
console.log(intersection([4, 9, 5], [9, 4, 9, 8, 4])); // Output: [9, 4]

Solution in Java:

Java
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // Convert the first array to a HashSet to remove duplicates and allow O(1) average-time complexity checks
        Set<Integer> set1 = new HashSet<>();
        for (int num : nums1) {
            set1.add(num);
        }

        // Initialize another HashSet to store the intersection
        Set<Integer> intersectionSet = new HashSet<>();

        // Iterate through the second array
        for (int num : nums2) {
            // If the number is in the first set, add it to the intersection set
            if (set1.contains(num)) {
                intersectionSet.add(num);
            }
        }

        // Convert the intersection set to an array
        int[] result = new int[intersectionSet.size()];
        int i = 0;
        for (int num : intersectionSet) {
            result[i++] = num;
        }

        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(Arrays.toString(solution.intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2}))); // Output: [2]
        System.out.println(Arrays.toString(solution.intersection(new int[]{4, 9, 5}, new int[]{9, 4, 9, 8, 4}))); // Output: [9, 4]
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int[] Intersection(int[] nums1, int[] nums2) {
        // Convert the first array to a HashSet to remove duplicates and allow O(1) average-time complexity checks
        HashSet<int> set1 = new HashSet<int>(nums1);
        
        // Initialize another HashSet to store the intersection
        HashSet<int> intersectionSet = new HashSet<int>();
        
        // Iterate through the second array
        foreach (int num in nums2) {
            // If the number is in the first set, add it to the intersection set
            if (set1.Contains(num)) {
                intersectionSet.Add(num);
            }
        }
        
        // Convert the intersection set to an array
        return intersectionSet.ToArray();
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular