Skip to main content

Intersection of Two Arrays - LeetCode Daily Challenge

Prerna Sharma

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.

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.

Try here before watching the video.

Video Explanation

Java Code

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        List<Integer> tempResult = new ArrayList<>();
        Map<Integer, Integer> seen = new HashMap<>();

        for(int num : nums1) {
            seen.put(num, 1);
        }

        for(int num : nums2) {
            if(seen.containsKey(num) && seen.get(num) == 1) {
                seen.put(num, 0);
                tempResult.add(num);
            }
        }

        int[] result = new int[tempResult.size()];
        for(int i = 0; i < tempResult.size(); i++) {
            result[i] = tempResult.get(i);
        }

        return result;

    }
}

C++ Code

class Solution {
public:
    std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) {
        unordered_map<int, int> seen;
        vector<int> tempResult;

        for (int num : nums1) {
            seen[num] = 1;
        }

        for (int num : nums2) {
            if (seen.count(num) && seen[num] == 1) {
                seen[num] = 0;
                tempResult.push_back(num);
            }
        }

        return tempResult;
    }
};

Python Code

class Solution:
    def intersection(self, nums1, nums2):
        seen = {}
        temp_result = []

        for num in nums1:
            seen[num] = 1

        for num in nums2:
            if num in seen and seen[num] == 1:
                seen[num] = 0
                temp_result.append(num)

        return temp_result

Javascript Code

var intersection = function(nums1, nums2) {
    let seen = {};
    let tempResult = [];

    for (let num of nums1) {
        seen[num] = 1;
    }

    for (let num of nums2) {
        if (seen[num] === 1) {
            seen[num] = 0;
            tempResult.push(num);
        }
    }

    return tempResult;
};

Go Code

func intersection(nums1 []int, nums2 []int) []int {
    seen := make(map[int]int)
    var tempResult []int

    for _, num := range nums1 {
        seen[num] = 1
    }

    for _, num := range nums2 {
        if seen[num] == 1 {
            seen[num] = 0
            tempResult = append(tempResult, num)
        }
    }

    return tempResult
}

Complexity Analysis

Time Complexity: O(M + N), where M and N are the lengths of nums1 and nums2 array. It's because we are iterating through both arrays.
Space Complexity: O(M), this is because we are storing all the elements of nums1 in a map.