We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Intersection of Multiple Arrays

Number: 2331

Difficulty: Easy

Paid? No

Companies: Amazon, Uber


Problem Description

Given a 2D integer array nums where each nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.


Key Insights

  • We need to compute the intersection of multiple arrays.
  • Each array contains distinct integers, so there are no duplicate elements within any individual array.
  • Efficient solutions can use sets (or hash tables) to compute intersections.
  • After finding the common elements, the answer must be sorted in ascending order.
  • The total number of integers across all arrays is relatively small, making simple iterative approaches viable.

Space and Time Complexity

Time Complexity: O(N * L + K log K) where N is the number of arrays, L is the average length of each array, and sorting K common elements takes O(K log K).
Space Complexity: O(M) where M is the maximum number of distinct elements (M <= 1000).


Solution

We approach the problem using set intersection. First, initialize a set with the elements from the first array. Then, iterate over the remaining arrays, updating the set to keep only elements present in both the current set and the next array. Finally, convert the resulting set into a sorted list before returning it. This method is efficient due to the small input size and leverages built-in set operations for clarity and conciseness.


Code Solutions

def intersection_of_arrays(nums):
    # Initialize the intersection set with the first array's elements
    common_elements = set(nums[0])
    # Iterate over the remaining arrays and compute the intersection
    for arr in nums[1:]:
        common_elements &= set(arr)  # Update with intersection
    # Return the sorted list of common elements
    return sorted(common_elements)

# Example usage:
nums = [[3,1,2,4,5], [1,2,3,4], [3,4,5,6]]
print(intersection_of_arrays(nums))  # Output: [3, 4]
← Back to All Questions