Given a sorted array of integers (in non-decreasing order) and a target value, find two numbers that add up to the target. Return their 1-indexed positions. You must use only constant extra space.
For example, given numbers = [2, 7, 11, 15] and target = 9, the output is [1, 2] because numbers[0] + numbers[1] = 2 + 7 = 9.
Explain why the two-pointer approach works on sorted input, prove that it does not miss the optimal pair, and analyze complexity.
How to approach it
- Hint 1
The array is sorted. If the sum of two elements is too large, what should you adjust? If too small?
- Hint 2
Start with pointers at both ends. The left pointer gives you the smallest available value, the right gives the largest.
- Hint 3
When the sum is too large, moving the right pointer left decreases it. When too small, moving the left pointer right increases it. Why does this never skip the answer?
Ready to answer it out loud?
Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.
Practising needs an invite code. Join the waitlist and we’ll send you one.