LC 167
LeetCode 167 · Medium

Two Sum II — Input Array Is Sorted

On a sorted array, return the 1-indexed positions of the two numbers adding to the target.


Try it

Step through the core mechanic. The simulator below runs the two pointers shape this problem is built on.

Interactive · Two-pointers walkthrough Two Sum II (sorted): find a pair that sums to target.
0
1
L
1
2
2
3
3
5
4
8
5
11
6
14
7
17
8
21
R
start: a[L] + a[R] = 22
step 1 / 4
Why two pointers works. Because the array is sorted, every position pair (L, R) is uniquely determined by its sum's relation to the target. If sum < target, moving L right is the only way to grow the sum without moving R; if sum > target, moving R left is the only way to shrink it. The pointers never need to revisit — that's why it's O(n) instead of the obvious O(n²).

The approach

Pointers at both ends. If the sum is too small, advance the left pointer; too large, retreat the right. Sortedness makes each move provably correct, so no hash map is needed.

AspectValue
PatternTwo pointers
Recognise it byPair sum on a SORTED array, O(1) space.
Time complexityO(n)
Space complexityO(1)
DifficultyMedium

Who asks it

Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.