Note that len(arr)-1
helps to get the last index possible in an array.
Also observe that when we start, pointer_one
points to the first element of the array, and pointer_two
points to the last element.
This won't always be the case with this technique (we'll explore the sliding window concept later, which uses two pointers but have them move in a different direction). For our current purposes, it is more efficient to start wide, and iteratively narrow in (particularly if the array is sorted).
1var twoSum = function (arr, target) {
2 for (let i = 0, j = arr.length - 1; i < j; ) {
3 // logic to find the two numbers that add up to target
4 }
5};