General • Asked almost 5 years ago by Anonymous
This is the main discussion thread generated for Using The Two Pointer Technique.
[deleted]
let arr = [1, 2, 3, 4, 5];
let target = 7;
function two_sum(arr, target) {
let n = 0;
let k = 1;
let pointerOne = arr[n];
let pointerTwo = arr[arr.length - k];
console.log(pointerOne, pointerTwo);
let finalArray = [];
while (n <= k) {
sum = pointerOne + pointerTwo;
console.log(sum);
if (sum == target) {
return finalArray.concat([pointerOne, pointerTwo]);
} else if (sum < target) {
n += 1;
} else {
k += 1;
}
}
return finalArray;
}
console.log(two_sum(arr, target));
I tried to convert the Python script in the section below for the two_sum function into javascript. My return is written to return an array of arrays that contain sets that meet the target value. For some reason the code works when I set arr = [2,5] but if I set arr=[1,2,3,4,5] with the target of 7 then the pointers stop in the while loop and it doesnt keep searching for pairs... Anyone have any thoughts?
Hey Rudy,
It's because of these lines:
let n = 0;
let k = 1;
and while (n <= k) {
I believe you intended to set k
to be the last index of the input array. But because it was set to 1
, we evaluated while (0 <= 1)
, and thus only one iteration was done. If k
was instead arr.length - 1
(5 - 1
or 4
), you'd evaluate while (0 <= 4)
and have several more iterations to move the two pointers.
Thanks Jake, yup you were right, I needed to update k to arr.length. I also updated my incrementing and decrementing counters from n and k to pointerOne and pointerTwo.
Here is the code below for those curious:
let arr = [1, 2, 3, 4, 5];
let target = 7;
function two_sum(arr, target) {
let n = 0;
let k = arr.length - 1;
let pointerOne = arr[n];
let pointerTwo = arr[k];
let finalArray = [];
while (n < k) {
sum = pointerOne + pointerTwo;
if (sum == target) {
return finalArray.concat([pointerOne, pointerTwo]);
} else if (sum < target) {
pointerOne += 1;
} else {
pointerTwo -= 1;
}
}
return finalArray;
}
console.log(two_sum(arr, target));