The task is to find the elements that exist in both arrays, given two sorted arrays.
The boilerplate code
function intersect(arr1, arr2) {
// your code here
}
Because the 2 arrays are sorted, both of them can be walked through at the same time. Start at the beginning of both arrays using two pointers
let i = 0, j = 0;
const result = [];
Compare the current elements, if they are equal, it means an element present in both arrays has been found.
while (i < arr1.length && j < arr2.length) {
if (arr1[i] === arr2[j]) {
result.push(arr1[i]);
i++;
j++;
}
}
If the element in the first array is smaller, push that pointer forward.
else if (arr1[i] < arr2[j]) {
i++;
}
If the element in the second array is smaller, push that pointer forward
else {
j++;
}
Continue until the end of the array is reached.
The final code
function intersect(arr1, arr2) {
// your code here
let i = 0; j = 0;
const result = [];
while(i < arr1.length && j < arr2.length) {
if(arr1[i] === arr2[j]) {
result.push(arr1[i]);
i++;
j++;
} else if(arr1[i] < arr2[j]) {
i++;
}
else {
j++;
}
}
return result;
}
That's all folks!
Top comments (0)