24 March 2024

Medium

167. Two Sum II - Input Array Is Sorted

Link: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted

Description: Given an array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.

Solution:

We can use two pointers to solve this problem. We will start with the first and last elements of the array. Iterate until the first pointer is less than the second pointer. If the sum of the two elements is equal to the target, return the indices of the two elements. If the sum is less than the target, move the first pointer to the right by one, because the array is sorted in non-decreasing order and the sum will be greater if we move the first pointer to the right. If the sum is greater than the target, move the second pointer to the left by one, because the array is sorted in non-decreasing order and the sum will be smaller if we move the second pointer to the left.

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */

var twoSum = function (numbers, target) {
  let start = 0
  let end = numbers.length - 1

  while (start < end) {
    const first = numbers[start]
    const second = numbers[end]
    const sum = first + second

    if (sum === target) {
      return [start + 1, end + 1]
    } else if (sum < target) {
      start += 1
    } else if (sum > target) {
      end -= 1
    }
  }
}