Two Sum II

35 min · twoSumSorted()

This is Two Sum with one crucial upgrade: the array is already sorted in non-decreasing order — and that changes everything about the right solution.

Given a 1-indexed array numbers sorted in non-decreasing order and an integer target, find the two positions whose values add up to target. Return them as [i, j] with i < j, using 1-based indexing.

  • Exactly one valid pair exists for every input.
  • You may not use the same position twice.
  • Aim for constant extra space — that's the point of this variant.

Constraints

  • 2 <= numbers.length <= 100_000
  • -1_000_000_000 <= numbers[i], target <= 1_000_000_000
  • numbers is sorted in non-decreasing order.
  • Exactly one solution exists.

Hints

What did sorting buy you?

In unsorted Two Sum you paid O(n) memory for a hash map. Sorted order is information — it should be able to replace that memory. How does the sum change when you swap in a bigger number? A smaller one?

Start at both ends

Point left at the smallest value and right at the largest. Their sum is either right, too small, or too big. Two of those three cases tell you a pointer that can be moved — and why it's safe to move it.

The safety argument

If numbers[left] + numbers[right] > target, then numbers[right] is too big to pair with ANY value at or right of left — every candidate partner is ≥ numbers[left]. So right can retire inward without losing the answer.

Follow-up

The exact same converging movement solves Container With Most Water and 3Sum. Once the "which pointer moves, and what makes that safe" argument clicks here, those two are half-done.

Visible cases

Examples

Example 1

ready
Input
numbers = [
  2,
  7,
  11,
  15
]
target = 9
Expected
[
  1,
  2
]
Why
2 + 7 = 9 → positions 1 and 2 (1-indexed)

Example 2

ready
Input
numbers = [
  2,
  3,
  4
]
target = 6
Expected
[
  1,
  3
]
Why
2 + 4 = 6; the 3 can't pair with itself

Example 3

ready
Input
numbers = [
  -1,
  0
]
target = -1
Expected
[
  1,
  2
]
Why
negative values are fair game

Interview signal

Asked at

AmazonMicrosoftApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite