TRT
Sign in
mediumAdvancedLeetCode#converging pointers

Two sum II: input array is sorted

Find two numbers in a sorted array that add up to a target, in O(n) time and O(1) space, with converging pointers.

The Runtime Theory Team1 min read
Taught inTwo pointersPro — members onlyOn a sorted array, two indexes moving toward each other can find pairs with a given sum in one pass, because every move rules out a whole row of candidate pairs. The same argument powers three-sum, container problems and trapping rain water.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innumbers = [2, 7, 11, 15], target = 9

out[1, 2]

innumbers = [2, 3, 4], target = 6

out[1, 3]

innumbers = [-1, 0], target = -1

out[1, 2]

Given a 1-indexed sorted array, return the indexes of the two numbers that add up to the target. Exactly one solution exists; use O(1) extra space.

Before you code

A hash map would work but uses O(n) space. The sorted order lets two pointers rule out a whole row of pairs at every step.

Hints

  1. Start at both ends.
  2. Sum too small: move the left pointer right. Too big: move the right pointer left.
  3. Return 1-based indexes.

Production & complexity notes

When solving Two sum II: input array is sorted on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.

What it practices

Why each move is safe, from Two pointers.

Not started

Sign in to save your learning progress.

Sign in to save