Two pointer algorithm in Javascript🤩

The two pointer algorithm can be really usefull.

Say we have a array (it MUST be sorted) of ints: [2,5,11,23,45,46,76,90,111].
The task is to find two numbers that add up to x, in our case, lets say x is 68.
As you can see from the array, the answer should be [3,4]. But how can we find the index of the two numbers that add up to 68? We could loop over the array, and loop again inside that loop. That would give us a big o On2. That is slow…

So we will use the two pointer algorithm. It starts with a pointer in each end of the array..i call it left and right. And moves them until the desired result is found.

Take a look at the code below:

--

--