Two Sum II – Input Array Is Sorted | LeetCode 167

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard

Here is the full implementation.

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
let twoSum = function(numbers, target) {
  let leftPointer = 0;
  let rightPointer = numbers.length - 1;
  let result = [];

  while (leftPointer < rightPointer) {
    let leftElement = numbers[leftPointer];
    let rightElement = numbers[rightPointer];

    if (leftElement + rightElement === target) {
      result.push(leftPointer + 1);
      result.push(rightPointer + 1);
      break;
    } else if (leftElement + rightElement > target) {
      rightPointer--;
    } else {
      leftPointer++;
    }
  }

  return result;   
};