Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Intersection of three sorted arrays in JavaScript
We are required to write a JavaScript function that takes in three arrays of integers all sorted in an increasing order. The function should then construct and return an array that contains only those elements that are present in all three arrays.
For example, if the input arrays are:
const arr1 = [4, 7, 8, 11, 13, 15, 17]; const arr2 = [1, 3, 4, 13, 18]; const arr3 = [2, 4, 7, 8, 9, 10, 13];
Then the output should be:
const output = [4, 13];
Three-Pointer Approach
Since all three arrays are sorted, we can use a three-pointer technique. We maintain one pointer for each array and compare elements at current positions:
const arr1 = [4, 7, 8, 11, 13, 15, 17];
const arr2 = [1, 3, 4, 13, 18];
const arr3 = [2, 4, 7, 8, 9, 10, 13];
const intersectThree = (arr1 = [], arr2 = [], arr3 = []) => {
let curr1 = 0;
let curr2 = 0;
let curr3 = 0;
const res = [];
while((curr1 < arr1.length) && (curr2 < arr2.length) && (curr3 < arr3.length)){
// If all three elements are equal, add to result
if((arr1[curr1] === arr2[curr2]) && (arr2[curr2] === arr3[curr3])){
res.push(arr1[curr1]);
curr1++;
curr2++;
curr3++;
} else {
// Find the maximum element among current positions
const max = Math.max(arr1[curr1], arr2[curr2], arr3[curr3]);
// Advance pointers for arrays with smaller elements
if(arr1[curr1] < max){
curr1++;
}
if(arr2[curr2] < max){
curr2++;
}
if(arr3[curr3] < max){
curr3++;
}
}
}
return res;
};
console.log(intersectThree(arr1, arr2, arr3));
[4, 13]
How It Works
The algorithm works by:
- Comparing elements at current positions of all three arrays
- If all three are equal, add to result and advance all pointers
- If not equal, find the maximum and advance pointers of arrays with smaller elements
- Continue until any array is exhausted
Alternative: Set Intersection Approach
For smaller arrays or when simplicity is preferred over efficiency:
const intersectThreeSet = (arr1, arr2, arr3) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
return arr3.filter(num => set1.has(num) && set2.has(num));
};
console.log(intersectThreeSet(arr1, arr2, arr3));
[4, 13]
Time Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Three-Pointer | O(n + m + k) | O(1) |
| Set Intersection | O(n + m + k) | O(n + m) |
Conclusion
The three-pointer approach efficiently finds intersection by leveraging the sorted property of arrays. It's optimal for memory usage and performs well even with large datasets.
