Intersection of Multiple Arrays - 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 in each array of nums sorted in ascending order.

Each sub-array contains only distinct positive integers, and we need to find the intersection of all arrays - the numbers that appear in every single array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
💡 Note: Numbers 3 and 4 appear in all three arrays: [3,1,2,4,5] contains 3,4; [1,2,3,4] contains 3,4; [3,4,5,6] contains 3,4
Example 2 — Single Element
$ Input: nums = [[1,2,3],[4,5,6]]
Output: []
💡 Note: No numbers appear in both arrays - first array has [1,2,3] and second has [4,5,6] with no overlap
Example 3 — All Same
$ Input: nums = [[1,2,3,4,5],[1,2,3,4,5]]
Output: [1,2,3,4,5]
💡 Note: Both arrays are identical, so all elements [1,2,3,4,5] appear in every array

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i].length ≤ 1000
  • 1 ≤ nums[i][j] ≤ 1000
  • All the values of nums[i] are unique

Visualization

Tap to expand
Intersection of Multiple Arrays INPUT nums[0]: 3 1 2 4 5 nums[1]: 1 2 3 4 nums[2]: 3 4 5 6 Input Structure: 3 arrays with distinct positive integers n = 3 arrays Find common in ALL ALGORITHM STEPS 1 Count Frequencies Use HashMap to count each number occurrence 2 Iterate All Arrays For each num in each array: count[num]++ 3 Filter by Count Keep nums where count == n (3 arrays) 4 Sort Result Sort ascending and return the result Frequency Count: 1:2 2:2 3:3 4:3 5:2 6:1 3 and 4 appear 3 times (equal to n=3) --> OK FINAL RESULT Numbers in ALL arrays: 3,4 common arr0 arr1 arr2 Output: [3,4] Verification: OK 3 appears in all 3 arrays 4 appears in all 3 arrays Key Insight: Since all integers in each array are distinct, a number appears in ALL arrays if and only if its frequency count equals the total number of arrays (n). This allows O(n*m) time solution using a HashMap, where n = number of arrays and m = average array length. TutorialsPoint - Intersection of Multiple Arrays | Optimal Solution (HashMap Counting) Time: O(n*m + k*log(k)) | Space: O(k) where k = unique numbers
Asked in
Amazon 25 Facebook 18 Google 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen