CodeArchon

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
0
lo
7
1
11
2
15
3
hi
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).

1def find_sorted_pair(prices: list[int], target: int) -> list[int]:
2 lo, hi = 0, len(prices) - 1
3 while lo < hi:
4 s = prices[lo] + prices[hi]
5 if s == target:
6 return [lo + 1, hi + 1]
7 if s < target:
8 lo += 1
9 else:
10 hi -= 1
11 return []
Variables
target=9
lo=0
hi=3

How to think about it

  1. Sorted input is a huge hint: the sum reacts predictably to pointer moves.
  2. Start pointers at both ends.
  3. If prices[lo] + prices[hi] = target → done.
  4. If sum < target → advance lo (we need more).
  5. If sum > target → retreat hi (we need less).
  6. 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