#2248
Intersection of Multiple Arrays
EasyArrayHash TableSortingCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a HashMap to count occurrences of each integer across all arrays. This is efficient because it allows us to determine which integers appear in every array with a single pass through the data.
⚙️
Algorithm
4 steps- 1Step 1: Create a HashMap to count occurrences of each integer.
- 2Step 2: Iterate through each array and update the count for each integer in the HashMap.
- 3Step 3: Collect integers that have a count equal to the number of arrays.
- 4Step 4: Sort the result list before returning it.
solution.py9 lines
1from collections import defaultdict
2
3def intersection(nums):
4 count = defaultdict(int)
5 for arr in nums:
6 for num in set(arr):
7 count[num] += 1
8 result = [num for num, cnt in count.items() if cnt == len(nums)]
9 return sorted(result)ℹ
Complexity note: The time complexity is O(n) because we only pass through the data a couple of times (once to count and once to filter). The space complexity is O(n) due to the HashMap storing counts of each integer.
- 1Using a HashMap allows efficient counting of occurrences across multiple arrays.
- 2Sorting the result at the end ensures the output is in ascending order.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.