<AI/>
enru
Все статьи

Two sum II - input array is sorted

LeetCode 167: Find two numbers in a sorted array that add up to the target using two pointers and constant memory.

Сложность
Средняя
Опубликовано
Темы
#two pointers
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an integer array nums sorted in ascending order. Write a function twoSum that finds two numbers in the array whose sum equals the target number target. The function should return an array with the indices of the elements that satisfy the condition. Indices start at one.

Constraints

  • The array contains from 2 to 3 * 104 unique values
  • Values are in the range from -1000 to 1000
  • The array is sorted in ascending order
  • target is in the range from -1000 to 1000
  • There is always exactly one solution

Examples

Input

nums = [2, 5, 7, 15]
target = 9

Answer: [1, 3]

The sum of 2 and 7 is 9, so index1 = 1 and index2 = 3. We return [1, 3].

Solution

The extra conditions make this problem much simpler:

  • the array is sorted in ascending order;
  • there are no duplicate values in the array.

Thanks to these conditions, we can solve the problem with two pointers using the following algorithm.

  1. Create two pointers that store indices. Set left to 0 and right to the index of the last element.
  2. Run a loop that stops when left becomes greater than or equal to right, i.e. when the pointers meet.
  3. On each iteration compute the sum of the elements at left and right and compare it with target:
    • If the sum equals target, we've found the numbers. Return their indices, adding one to each.
    • If the sum is greater than target, we've added numbers that are too large and need smaller ones. We can decrease the sum by taking the number to the left of the one at right. Since the array is sorted in ascending order and has no duplicates, the number to the left of right is guaranteed to be smaller. Decrement right by 1.
    • If the sum is less than target, we've added numbers that are too small and need larger ones. We can increase the sum by taking the number to the right of the one at left. Since the array is sorted in ascending order and has no duplicates, the number to the right of left is guaranteed to be larger. Increment left by 1.

This way we go through all the relevant combinations and find the answer.

typescript
export const twoSum = (nums: number[], target: number): number[] => {
  // Set the left pointer to index zero
  let left = 0;
 
  // Set the right pointer to the index of the last element
  let right = nums.length - 1;
 
  // Loop until `left` and `right` meet
  while (left < right) {
    const sum = nums[left] + nums[right];
 
    if (sum === target) {
      return [left + 1, right + 1];
    } else if (sum > target) {
      right--;
    } else {
      left++;
    }
  }
 
  // If nothing was found, return [-1, -1]
  return [-1, -1];
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

O(n), since in the worst case we go over all elements of the array.

Space Complexity

O(1), since we only use a few variables to store the indices and the sum.