Two Gifts for One Card
Easy · Two Pointers · about 12 min
You have a gift card worth exactly card rupees and a shop's price list prices, sorted from cheapest to most expensive (prices are whole numbers, 0 or more, and may repeat).
Pick two different items (two different positions in the list) whose prices add up to exactly card. Return their prices as [smaller, larger].
- If several pairs work, return the pair whose smaller price is the lowest.
- If no pair works (or there are fewer than two items), return
[]. - One item cannot be used twice, but two items may have the same price.
Examples:
gift_card_pair([1, 3, 4, 6, 9], 10) → [1, 9] (4 + 6 also works, but 1 is lower)
gift_card_pair([3, 5, 8], 6) → [] (3 + 3 would need the same item twice)
Aim for O(n) time and O(1) extra space.
Hints
- Put one pointer on the first price and one on the last price.
- If the two prices add up to too little, which pointer can make the total bigger? If too much, which one makes it smaller?
- Keep going only while the left pointer is strictly before the right one, so an item is never paired with itself.
Learn the pattern first: the Two Pointers lesson.
More Two Pointers problems
- Mirror Sign Check (Easy)
- Squash Repeated Readings (Easy)
- Ledger Entries That Cancel Out (Medium)
- Biggest Tank Between Two Posts (Medium)
- Three Weights Closest to the Mark (Medium)
- Rain Caught on a Rooftop Row (Hard)