Taro Logo

Intersection of Two Arrays

#174 Most AskedEasy
Topics:
ArraysTwo PointersBinary Search

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.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected return type and format if there is no intersection between the two arrays?
  2. Can the input arrays contain negative numbers, zeros, or duplicates?
  3. What are the expected maximum lengths of the two arrays?
  4. Should the result be returned in any particular order?
  5. Are the input arrays guaranteed to fit entirely in memory?

Brute Force Solution

Approach

Imagine you have two separate buckets filled with different items, and you want to find out which items appear in both buckets. The brute force approach involves picking up every single item from the first bucket and comparing it against every single item in the second bucket one by one.

Here's how the algorithm would work step-by-step:

  1. Take the very first item from your first bucket.
  2. Carry this item over to the second bucket and look at every item inside that second bucket one at a time to see if there is a match.
  3. If you find a matching item, set it aside in a special collection for shared items, making sure not to duplicate it if you already collected that same item earlier.
  4. Move on to the next item in the first bucket and repeat the exact same process of checking it against every item in the second bucket.
  5. Continue this process for every remaining item in the first bucket until no items are left to check.
  6. Finally, reveal your special collection containing all the items that appeared in both buckets.

Code Implementation

def intersection_of_two_arrays(first_bucket, second_bucket):
    shared_items_collection = []

    # We iterate through every item to ensure all possible matches are evaluated
    for first_bucket_item in first_bucket:
        
        for second_bucket_item in second_bucket:
            
            if first_bucket_item == second_bucket_item:
                
                # We check presence to avoid duplicates in our final shared collection
                if first_bucket_item not in shared_items_collection:
                    shared_items_collection.append(first_bucket_item)

    # Returning the final collection gives us the complete intersection result
    return shared_items_collection

Big(O) Analysis

Time Complexity
O(n²) – For each of the n elements in the first bucket, we iterate through all elements in the second bucket to check for a match. If both buckets contain roughly n elements, this requires comparing every item in the first list against every item in the second list. This nested iteration leads to approximately n times n operations. When we simplify this quadratic growth by dropping constants, the total time complexity is O(n²).
Space Complexity
O(N) – The space complexity is driven by the special collection used to store the unique shared items and any intermediate tracking sets. In the worst-case scenario where all elements are unique and shared between the two buckets of size N, the collection grows proportionally to the number of elements. Therefore, the auxiliary memory scales linearly with the input size N.

Optimal Solution

Approach

To efficiently find the common items between two collections, the optimal approach relies on a mental filter system. Instead of constantly comparing every item against every other item, we can first make a unique membership list of one collection so we can instantly check items from the second collection.

Here's how the algorithm would work step-by-step:

  1. Take the items from the first group and place them into a special tracker that records each unique item present.
  2. Look through the items in the second group one by one.
  3. For each item in the second group, check if it is already present in your tracker.
  4. If the item is found in the tracker, collect it as a common item and immediately remove it from the tracker to prevent counting duplicates.
  5. If the item is not in the tracker, simply ignore it and move on to the next item.
  6. Continue this quick verification process until every item in the second group has been checked, leaving you with the final collection of shared items.

Code Implementation

def intersection(first_array, second_array):
    # Using a set provides O(1) average time complexity for membership lookup operations.
    unique_tracker_set = set(first_array)
    
    collected_intersection = []
    
    for current_item in second_array:
        # Checking existence and removing ensures each common element is counted only once.
        if current_item in unique_tracker_set:
            collected_intersection.append(current_item)
            
            unique_tracker_set.remove(current_item)
            
    return collected_intersection

Big(O) Analysis

Time Complexity
O(n + m) – First, we iterate through the n elements of the first array to insert them into a hash set, which takes O(n) time. Next, we iterate through the m elements of the second array to check for membership and collect intersections, taking O(m) time. Combining these linear passes results in approximately n + m operations, which simplifies to O(n + m).
Space Complexity
O(n) – The auxiliary space is driven by the special tracker hash map used to store unique items from the first group, where N represents the number of elements in that first collection. As the input size grows, this tracking structure requires memory proportional to the number of distinct elements it holds. Additionally, the final collection used to gather the shared items consumes extra space, though it is bounded by the size of the smaller input. Therefore, the total extra memory scales linearly with the input size, resulting in a space complexity of O(N).

Edge Cases

One or both input arrays are empty or null
How to Handle:
Return an empty array immediately since no intersection can exist between empty datasets
Arrays containing duplicate values
How to Handle:
Use a set data structure to automatically filter out duplicates and ensure the final intersection contains only unique elements
Arrays with completely disjoint values having no intersection
How to Handle:
The result collection remains empty and the algorithm returns it safely without throwing errors
Arrays containing negative numbers and zero
How to Handle:
Standard hash set lookups handle negative integers and zero identically to positive numbers without any special offset logic
Extremely large arrays exceeding typical memory limits
How to Handle:
Stream or two-pointer sorting approaches can be utilized to process elements iteratively rather than loading everything into memory
One array is significantly larger than the other
How to Handle:
Convert the smaller array into a hash set first to minimize memory consumption and optimize lookup time
Inputs with extreme boundary integer values
How to Handle:
Standard hash set implementations handle 32-bit or 64-bit integer limits natively without arithmetic overflow risks
Both arrays are identical and contain all duplicate elements
How to Handle:
Using sets for both arrays reduces them to unique sets before finding the intersection, returning the deduplicated single instance of each element
0/245 completed