Problem
Given a 2D integer array nums
where nums[i]
is a non-empty array of
distinct positive integers, return the list of integers that are present ineach array of nums
sorted inascending order.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 1000
1 <= sum(nums[i].length) <= 1000
1 <= nums[i][j] <= 1000
- All the values of
nums[i]
are unique.
Solution
Method 1 – Hash Map Counting
Intuition
We want to find elements that appear in every array. By counting the occurrences of each number across all arrays, we can select those that appear in all of them.
Approach
- Use a hash map to count the number of arrays each integer appears in.
- For each array, add 1 to the count for each unique integer.
- After processing all arrays, collect integers whose count equals the number of arrays.
- Sort the result in ascending order.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * k + N log N)
— m is the number of arrays, k is the average array length, N is the number of unique elements (for sorting). - 🧺 Space complexity:
O(N)
— For the hash map and result array.