mediumTwo PointersAmazonMicrosoft
Sorted Price Pair
A sorted price catalog is on your desk. Find two line-items whose prices add up to a budget target.
Given a 1-indexed sorted integer array `prices` and an integer `target`, return the 1-indexed positions of two elements that add up to the target. Exactly one solution is guaranteed; use O(1) extra space.
Choose approach
2
0lo
7
111
215
3hi
1/7
Narrationstep 1 of 7
Prices are sorted. Place lo at 0 and hi at 3. Sliding them inward lets us hit the target in O(n).
Variables
target=9
lo=0
hi=3
How to think about it
- Sorted input is a huge hint: the sum reacts predictably to pointer moves.
- Start pointers at both ends.
- If prices[lo] + prices[hi] = target → done.
- If sum < target → advance lo (we need more).
- If sum > target → retreat hi (we need less).
- Each pointer moves at most n times → O(n), O(1) space.
Edge cases to catch in interview
- Negative numbers — the arithmetic still works.
- Target equal to twice an element — only hits if a duplicate exists adjacent in sorted order.
- Pointers crossing means no solution (the problem guarantees one exists in practice).
Examples
Example 1
[1, 2]{"prices":[2,7,11,15],"target":9,"values":[2,7,11,15]}
2 + 7 = 9.
Example 2
[1, 3]{"prices":[2,3,4],"target":6,"values":[2,3,4]}
2 + 4 = 6.
Example 3
[1, 2]{"prices":[-1,0],"target":-1,"values":[-1,0]}
-1 + 0 = -1.
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed