Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

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.

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.

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar
All Blog Posts