Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Using The Two Pointer Technique (Main Thread)

General • Asked over 4 years ago by Anonymous

Jake from AlgoDaily Commented on Dec 28, 2019:

This is the main discussion thread generated for Using The Two Pointer Technique.

Anonymous Commented on Dec 28, 2019:

[deleted]

Rudy Commented on Jan 11, 2021:
SNIPPET
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?

Jake from AlgoDaily Commented on Jan 11, 2021:

Hey Rudy,

It's because of these lines:

js
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.

Rudy Commented on Jan 11, 2021:

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:

SNIPPET
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));