Given a 2D integer array nums
where nums[i]
is a list of integers, return a list containing all the integers that are present in each and every array of nums
sorted in ascending order.
nums
is a list of lists, where each inner list contains integers.1 <= nums.length <= 1000
1 <= nums[i].length, nums[i][j] <= 1000
nums[i][j] <= 1000
.1 <= nums.length
and 1 <= nums[i].length
), no subarray or the main array will be empty.intersection_of_arrays
which will take a list of lists as input.set
to keep track of the intersection:
from typing import List
def intersection_of_arrays(nums: List[List[int]]) -> List[int]:
if not nums:
return []
# Start with the set of the first list
intersection_set = set(nums[0])
# Find the intersection with all remaining lists
for arr in nums[1:]:
intersection_set &= set(arr)
# Return the sorted list of the result
return sorted(intersection_set)
# Example usage:
nums = [
[1, 2, 3],
[4, 5, 2],
[2, 8, 9]
]
print(intersection_of_arrays(nums)) # Output: [2]
Thus, the total complexity is:
The approach efficiently handles the problem within constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?