Ctrl K

Pair in a Sorted List

Medium
A shop's price list prices is already sorted in non-decreasing order. Pick two different items that together cost exactly budget. Return their positions [i, j], counting **from one**, with i < j. Exactly one such pair is guaranteed. The same item cannot be used twice, though two different items may have the same price. Try to use only O(1) extra memory; the fact that the list is sorted is the main hint.
Example 1
prices=[1, 4, 6, 9, 13], budget=15 → [3, 4]

6 + 9 = 15: those are positions 3 and 4, so the answer is [3, 4].

Example 2
prices=[-8, -2, 0, 5], budget=-3 → [1, 4]

-8 + 5 = -3, positions 1 and 4.

Example 3
prices=[2, 5, 5, 11], budget=10 → [2, 3]

Both 5s are needed; they are two different elements at positions 2 and 3.

Constraints
  • 2 ≤ len(prices) ≤ 3 · 10⁴
  • -1000 ≤ prices[i] ≤ 1000
  • prices is sorted in non-decreasing order
  • -1000 ≤ budget ≤ 1000
  • Exactly one valid pair exists
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTriples Under a Limit MediumSpot the Extra Copy MediumWarm Every Cabin MediumPairs With a Fixed Gap MediumStick Triples That Form a Triangle Medium
loading Python…
Input
prices=[1, 4, 6, 9, 13], budget=15
Expected
[3, 4]

Run checks the first 3 tests in your browser. Submit checks all 25 tests on the server, hidden ones included.