All coding questions

Two Sum II Sorted Input

medium
NeetCode 150arraystwo-pointers

Problem

Given a list of integers already sorted in non-decreasing order and a target, return the one-based positions of the two values that add up to the target. Use constant extra space.

Examples

Input: nums = [2, 7, 11, 15], target = 9
Output: [1, 2]
2 + 7 = 9, at one-based positions 1 and 2.
Input: nums = [2, 3, 4], target = 6
Output: [1, 3]
2 + 4 = 6.

Constraints

  • 2 <= nums.length <= 3 * 10^4
  • Array is sorted ascending
  • Exactly one solution exists
Hints(tap to reveal)
  • 1. Sortedness lets two pointers decide which side to move.
  • 2. If the sum is too big, shrink from the right.
Optimal approach(spoiler)
  1. Start one pointer at the left and one at the right.
  2. Compute the sum of the two pointed values.
  3. If it equals the target, return the one-based indices.
  4. If too large move the right pointer left, if too small move the left pointer right.
  5. O(n) time, O(1) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor