Intersection of Three Sorted Arrays - Problem
Given three integer arrays arr1, arr2, and arr3 that are sorted in strictly increasing order, your task is to find the intersection of all three arrays.
The intersection contains only the integers that appear in all three arrays. Return these common elements as a sorted array.
For example, if arr1 = [1,2,3,4], arr2 = [2,3,4,5], and arr3 = [3,4,5,6], then the intersection would be [3,4] since only 3 and 4 appear in all three arrays.
Key Points:
- All input arrays are already sorted in ascending order
- Elements must appear in ALL THREE arrays to be included
- Return result in sorted order (naturally sorted due to input constraints)
Input & Output
example_1.py โ Basic intersection
$
Input:
arr1 = [1,2,3,4], arr2 = [2,3,4,5], arr3 = [3,4,5,6]
โบ
Output:
[3,4]
๐ก Note:
Elements 3 and 4 appear in all three arrays. Element 1 only appears in arr1, element 2 appears in arr1 and arr2 but not arr3, elements 5 and 6 don't appear in all three arrays.
example_2.py โ No common elements
$
Input:
arr1 = [1,2,3], arr2 = [4,5,6], arr3 = [7,8,9]
โบ
Output:
[]
๐ก Note:
No elements appear in all three arrays, so the intersection is empty.
example_3.py โ Single element intersection
$
Input:
arr1 = [1,2,3,4,5], arr2 = [1,3,5,7,9], arr3 = [1,4,7,10,13]
โบ
Output:
[1]
๐ก Note:
Only element 1 appears in all three arrays. Element 3 appears in arr1 and arr2 but not arr3, element 5 appears in arr1 and arr2 but not arr3, etc.
Visualization
Tap to expand
Understanding the Visualization
1
Start Position
All three dancers start at their first position
2
Find Synchronization
Check if all dancers are on the same beat
3
Advance Slower Dancers
Move dancers who are behind to catch up
4
Performance Moment
When synchronized, record the performance
5
Continue Dance
All dancers advance to next position
Key Takeaway
๐ฏ Key Insight: Like synchronized dancers, the three pointers move through sorted arrays, only "performing" (adding to result) when all three point to the same value!
Time & Space Complexity
Time Complexity
O(nยณ)
Three nested loops, each potentially iterating through all elements
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables, not counting output array
โ Linear Space
Constraints
- 1 โค arr1.length, arr2.length, arr3.length โค 1000
- 1 โค arr1[i], arr2[i], arr3[i] โค 2000
- All arrays are sorted in strictly increasing order
- No duplicate elements within each array
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code