Here is the function called sumZero, where it should return the sum of any two numbers in the array to sum upto zero. where the array is a sorted array.
My approach: Using 2 pointers approach, calling it as p1 and p2, where p1 points to zero, and p2 points to p1+1. and pointers get incremented
function sumZeroPointers(arr, p1, p2){
while(p2 < arr.length){
if(arr[p1] + arr[p2] === 0){
return [arr[p1] , arr[p2]]
}else{
p2++;
//When the pointer p2 reaches to the end of the array, then increment the pointer p1 by 1, and p2 to p1+1. and continue the while loop matching for the pairs.
if(p2 == arr.length){
p1++;
p2=p1+1;
}
}
}
}
function sumZero(array){
return sumZeroPointers(array, 0, 1)
}
console.log('sumZero : ', sumZero([-3, -2, -1, 0, 1, 2, 3])) //[-3, 3], indexed at (0, 6)
console.log('sumZero : ', sumZero([-3, -2, 0, 2, 3])) //[-2, 2], indexed at (1, 3)
console.log('sumZero : ', sumZero([-4, -2, 1, 2, 3]))//[-1, 1], indexed at (0, 2)
This works all good.
Now there is a another approach were the pointers p1 and p2 are marked at beginning(0) and end of the array (array.length-1), and incremented and decremented based on the sum value.
function sumZero1(arr){
let left = 0;
let right = arr.length - 1;
while(left < right){
let sum = arr[left] + arr[right];
if(sum === 0){
return [arr[left] , arr[right]]
} else if(sum > 0){
right--;
} else{
left++;
}
}
}
console.log('sumZero1 : ', sumZero1([-3, -2, -1, 0, 1, 2, 3])) //[-3, 3], indexed at (0, 6)
console.log('sumZero1 : ', sumZero1([-4, -2, 0, 2, 3])) //[-2, 2], indexed at (1, 3)
console.log('sumZero1 : ', sumZero1([-1, -2, 1, 2, 3]))//[-1, 1], indexed at (0, 2)
this too works well. But in my first approach also I do not see any flaws, readability wise approach 2 makes more sense, as the pointers are made to point at 0 and array.length-1 indexes, and incremented and decremented according to the sum.
What I want to understand is which one to follow, either two pointers pointing to one after another, yields efficient or optimized solution Or the approach 2.
Is there any tips / hints or points I should follow in this 2 pointer problems, like
- if the array is sorted, always follow pointer pointing at start and last indexes.
- if the array is not sorted , we can keep pointers next to each other or can follow pointer pointing at start and last indexes.
Can you please, let me know if there is any points / hints, I should remember when I follow this 2 pointer approach problems.
basically what I want to know is, is there some more points I should remember while solving 2-pointer problem. or which will be effective.