~/problems / Two pointers

Two Sum II (Sorted Input)

easy ~15 min

A shop lists its prices sorted from cheapest to most expensive. You hold a gift card worth card and want to buy exactly two different items whose prices add up to the card's value, leaving nothing unspent.

Write pick_two(prices: list[int], card: int) -> list[int] that returns the positions [i, j] (0-based, i < j) of the two items with prices[i] + prices[j] == card.

  • The input is built so that exactly one such pair of positions exists.
  • Two items can have the same price, but you can't buy the same item twice.
pick_two([3, 5, 8, 12, 20], 17)    # [1, 3]   (5 + 12)
pick_two([4, 4, 9], 8)             # [0, 1]
pick_two([1, 6, 30, 31], 61)       # [2, 3]

Constraints: 2 <= len(prices) <= 2 * 10^5; 1 <= prices[i] <= 10^9, in non-decreasing order; 2 <= card <= 2 * 10^9.

Trying every pair is O(n²) and far too slow at this size. Aim for O(n) time and O(1) extra space, using the fact that the list is sorted.

Show hint

look at the cheapest and the most expensive item together. If they add up to too little, is the cheapest item ever going to be part of the answer?

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc