Coding interview problems › Two Pointers
↔️ Two Pointers Medium
Two Sum II (Sorted Array)
Two Sum II on a sorted array explained: two pointers from both ends find the pair in O(n) time and O(1) space, why it never skips the answer, tested Python.
Also searched as: two sum sorted array two pointers · pair sum in sorted array
Try it live Free
Two Pointers
Watch two pointers turn an O(n²) double loop into one sweep, always moving the pointer that cannot be part of a better answer. Pair-sum on a sorted array uses exactly that rule.
The problem
A list of integers is sorted in non-decreasing order. Find two different positions whose values add up to target and return their indices 1-based. Exactly one answer exists, and you should use only constant extra space.
The key insight
Because the list is sorted, put one pointer on the smallest value and one on the largest. If their sum is too big, the only way to shrink it is to move the right pointer left; if too small, move the left pointer right. Each move throws away a value that cannot be part of any answer, so you never skip the real pair.
Step-by-step approach
- Set
i = 0andj = n - 1. - Compute
s = numbers[i] + numbers[j]. - If
s == target, return[i + 1, j + 1]. - If
s < target, moveiright; otherwise movejleft. - Repeat while
i < j.
Python solution
def two_sum_sorted(numbers, target):
i, j = 0, len(numbers) - 1
while i < j:
s = numbers[i] + numbers[j]
if s == target:
return [i + 1, j + 1] # 1-based indices
if s < target:
i += 1 # need a bigger sum
else:
j -= 1 # need a smaller sum
return []Complexity
Each iteration moves one pointer inward, so there are at most n - 1 iterations. Only two indices are stored.
Common mistakes
- Returning 0-based indices when the problem asks for 1-based ones.
- Moving both pointers at once, which can jump over the correct pair.
- Using a hash map: it works, but ignores the sorted order and uses O(n) space the problem rules out.
Frequently asked questions
What is the time and space complexity of Two Sum II?
O(n) time and O(1) space with two pointers. Binary search for each partner is O(n log n).
Why is it safe to discard numbers[j] when the sum is too big?
numbers[i] is the smallest value still available, and even with it the sum is too big. Every other partner for numbers[j] is at least as big, so numbers[j] cannot be in any answer.
How does this extend to 3Sum?
Fix one element, then run this two-pointer search on the rest for the remaining target. That gives O(n²) for 3Sum.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Two Pointers Two Pointers lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.