Medium Problems

167. Two Sum II - Input Array Is Sorted

Solutions

function twoSum(numbers: number[], target: number): number[] {
  let left = 0;
  let right = numbers.length - 1;
 
  while(left < right) {
      if(numbers[left] + numbers[right] === target) return [left+1, right+1]
 
      if(numbers[left] + numbers[right] > target) {
          right--;
      }
      if(numbers[left] + numbers[right] < target) {
          left++;
      }
  }  
 
  return [-1, -1];
};
Last Update: 12:08 - 16 April 2024
Array
Two Pointers
Binary Search

On this page