KatInterview

350. Intersection of Two Arrays II

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Using a Hash Map (Frequency Counter)

This problem asks for the intersection of two arrays, where the count of each element in the result should be the minimum of its counts in the two input arrays. A hash map is an effective tool for this kind of frequency-counting problem.

Solution

Intersection of Two Arrays II in Python

from collections import Counter

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Optimization: use the smaller array to build the counter to save space.
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1

        # Create a frequency map of the elements in the smaller array.
        counts = Counter(nums1)
        intersection = []

        # Iterate through the larger array.
        for num in nums2:
            # If the number exists in our frequency map and its count is positive.
            # Counter returns 0 for missing keys, so this check is sufficient.
            if counts[num] > 0:
                # Add it to our intersection list.
                intersection.append(num)
                # Decrement the count in the map.
                counts[num] -= 1
        
        return intersection

Intersection of Two Arrays II in Java

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // Optimization: use the smaller array to build the map to save space.
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1); // Recurse with swapped arrays
        }

        // Create a frequency map for the smaller array (nums1).
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums1) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        List<Integer> intersectionList = new ArrayList<>();
        // Iterate through the larger array (nums2) to find common elements.
        for (int num : nums2) {
            // If the element exists in the map and its count is positive.
            if (map.containsKey(num) && map.get(num) > 0) {
                intersectionList.add(num);
                map.put(num, map.get(num) - 1); // Decrement the count.
            }
        }

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

        return result;
    }
}

Intersection of Two Arrays II in C++

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        // Optimization: use the smaller array to build the map to save space.
        if (nums1.size() > nums2.size()) {
            return intersect(nums2, nums1); // Recurse with swapped arrays
        }

        // Create a frequency map for the smaller array (nums1).
        std::unordered_map<int, int> counts;
        for (int num : nums1) {
            counts[num]++;
        }

        std::vector<int> intersection;
        // Iterate through the larger array (nums2) to find common elements.
        for (int num : nums2) {
            // If the element exists in the map and its count is positive.
            if (counts.count(num) && counts[num] > 0) {
                intersection.push_back(num);
                counts[num]--; // Decrement the count.
            }
        }

        return intersection;
    }
};

Intersection of Two Arrays II in TypeScript

function intersect(nums1: number[], nums2: number[]): number[] {
    // Optimization: use the smaller array to build the map to save space.
    if (nums1.length > nums2.length) {
        return intersect(nums2, nums1); // Recurse with swapped arrays
    }

    // Create a frequency map for the smaller array (nums1).
    const counts = new Map<number, number>();
    for (const num of nums1) {
        counts.set(num, (counts.get(num) || 0) + 1);
    }

    const intersection: number[] = [];
    // Iterate through the larger array (nums2) to find common elements.
    for (const num of nums2) {
        const count = counts.get(num);
        // If the element exists in the map and its count is positive.
        if (count && count > 0) {
            intersection.push(num);
            counts.set(num, count - 1); // Decrement the count.
        }
    }

    return intersection;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.