codebrew.ai

Two Sum II - Input Array Is Sorted

Sorted input lets two pointers steer toward the target.

Approach

Start pointers at both ends. If their sum is too big, move the right pointer left; if too small, move the left pointer right. The sorted order guarantees each move discards only impossible pairs, so you find the answer in one pass with no extra memory.

Time complexity

O(n)

Space complexity

O(1)

Common mistake

Reusing the hash-map approach from Two Sum — it works but ignores the sorted structure that enables O(1) space here.

See it run, step by step

Generate an interactive lesson for Two Sum II - Input Array Is Sorted — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Two Sum II - Input Array Is Sorted

Related problems