Intersection of Three Sorted Arrays - Problem

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

Since all arrays are already sorted, we can take advantage of this property to find common elements efficiently.

Key points:

  • All arrays are sorted in strictly increasing order (no duplicates within each array)
  • We need elements that appear in all three arrays
  • The result should be sorted (naturally will be due to input being sorted)

Input & Output

Example 1 — Basic Case
$ Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
Output: [1,5]
💡 Note: Elements 1 and 5 appear in all three arrays. Element 1 is at index 0 in all arrays, and element 5 appears in positions: arr1[4], arr2[2], arr3[3].
Example 2 — No Common Elements
$ Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]
Output: []
💡 Note: No element appears in all three arrays, so the result is empty.
Example 3 — Single Common Element
$ Input: arr1 = [1,2,3], arr2 = [2,3,4], arr3 = [2,4,5]
Output: [2]
💡 Note: Only element 2 appears in all three arrays: arr1[1], arr2[0], arr3[0].

Constraints

  • 1 ≤ arr1.length, arr2.length, arr3.length ≤ 1000
  • -105 ≤ arr1[i], arr2[i], arr3[i] ≤ 105
  • All arrays are sorted in strictly increasing order

Visualization

Tap to expand
Intersection of Three Sorted Arrays INPUT arr1: 1 2 3 4 5 arr2: 1 2 5 7 9 arr3: 1 3 4 5 8 Three Pointers: i, j, k i j k All arrays sorted in increasing order ALGORITHM STEPS 1 Initialize Pointers Set i=0, j=0, k=0 for each array 2 Compare Elements Check if arr1[i] == arr2[j] == arr3[k] 3 If Equal: Add Result Add to result, move all three pointers 4 If Not Equal Move pointer of smallest element min(arr1[i], arr2[j], arr3[k]) Move smallest pointer forward Repeat until any array ends FINAL RESULT Trace: i=0,j=0,k=0: 1==1==1 OK i=1,j=1,k=1: 2,2,3 skip i=2,j=1,k=1: 3,2,3 skip i=2,j=2,k=1: 3,5,3 skip ... i=4,j=2,k=3: 5==5==5 OK Common Elements Found: 1, 5 Output: [1, 5] Key Insight: Since arrays are sorted, use three pointers technique. Compare values at all pointers: if equal, add to result; otherwise, increment the pointer with the smallest value. Time: O(n1 + n2 + n3) | Space: O(1) excluding output | Optimal linear scan approach TutorialsPoint - Intersection of Three Sorted Arrays | Optimal Three Pointers Approach
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
28.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