Intersection Of Two Arrays Problem

Intersection Of Two Arrays Problem Statement

Given two lists of numbers, find their intersection.

Example One

{
"a": [4, 2, 2, 3, 1],
"b": [2, 2, 2, 3, 3]
}

Output:

[2, 2, 3]

Example Two

{
"a": [6, 2, 4],
"b": [1, 5, 3, 7]
}

Output:

[]

Notes

  • The order of elements in the output list does not matter.
  • The frequency of any number in the intersection must be equal to the minimum of the frequency of that number in both the given lists.

Constraints:

  • 1 <= size of the input lists <= 105
  • -106 <= any element of the input lists <= 106

Code For Intersection Of Two Arrays Solution 1: List


"""
Asymptotic complexity in terms of the length of the given list `a` and `b`:
* Time: O(n * m).
* Auxiliary space: O(m).
* Total space: O(n + m).
"""

def get_intersection_with_maintained_frequency(a, b):
    """
    Args:
     a(list_int32): First list of integers.
     b(list_int32): Second list of integers.
    Returns:
     list_int32: List of integers representing the intersection with maintained frequency.
    """
    # Initialize a list to store the intersection.
    intersection = []

    # Copy list b to avoid mutating it while iterating.
    b_copy = b.copy()

    # Iterate over each element in list a.
    for element in a:
        # If the element is in list b, append it to the intersection and remove it from the copy of list b.
        if element in b_copy:
            intersection.append(element)
            b_copy.remove(element)

    # Return the intersection list.
    return intersection

Code For Intersection Of Two Arrays Solution 2: Dictionary


"""
Asymptotic complexity in terms of the length of the given list `a` and `b`:
* Time: O(n + m).
* Auxiliary space: O(m).
* Total space: O(n + m).
"""

def get_intersection_with_maintained_frequency(a, b):
    """
    Args:
     a(list_int32): First list of integers.
     b(list_int32): Second list of integers.
    Returns:
     list_int32: List of integers representing the intersection with maintained frequency.
    """

    # Create a dictionary for each list
    dict_a = {}
    for i in a:
        if i in dict_a:
            dict_a[i] += 1
        else:
            dict_a[i] = 1

    dict_b = {}
    for i in b:
        if i in dict_b:
            dict_b[i] += 1
        else:
            dict_b[i] = 1

    # Determine the length of each dictionary
    len_dict_a = len(dict_a)
    len_dict_b = len(dict_b)

    # Identify the smallest and largest dictionaries
    if len_dict_a < len_dict_b:
        smallest_dict = dict_a
        largest_dict = dict_b
    else:
        smallest_dict = dict_b
        largest_dict = dict_a

    # Initialize the intersection list
    intersection = []

    # Iterate through the items in the smallest dictionary
    for value, count_small in smallest_dict.items():
        # Check if the value is in the largest dictionary
        if value in largest_dict:
            # Get the count from the largest dictionary
            count_large = largest_dict[value]
            # Add the value to the intersection list, maintaining the frequency
            intersection.extend([value] * min(count_small, count_large))

    # Return the intersection list
    return intersection


Code For Intersection Of Two Arrays Solution 3: Hashmap

/*
Asymptotic complexity in terms of the length of list `a` (= `n`) and the length of list `b` (= `m`):
* Time: O(n + m).
* Auxiliary space: O(min(n, m)).
* Total space: O(n + m).
*/
vector<int> get_intersection_with_maintained_frequency(vector<int> &a, vector<int> &b) {

    if (a.size() > b.size()) {
        return get_intersection_with_maintained_frequency(b, a);
    }
    unordered_map<int, int> frequency_a;
    for (int i = 0; i < a.size(); i++) {
        frequency_a[a[i]]++;
    }

    vector<int> result;
    for (int i = 0; i < b.size(); i++) {
        if (frequency_a[b[i]] > 0) {
            result.push_back(b[i]);
            frequency_a[b[i]]--;
        }
    }
    return result;
}

We hope that these solutions to intersection of two arrays problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Add Two Numbers Represented By Lists Problem

Binary Tree Level Order Traversal Problem with Examples

Jump Game

Zigzag Sort Problem

Boggle Solver Problem

Shortest String Transformation Using A Dictionary Problem

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC