Pair in a sorted list
easy
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
Like Pair to target, but this time the prices are sorted from smallest to largest.
Return the positions of the two different items whose prices add up to exactly budget, smaller position first.
Because the list is sorted, you can solve this using only a couple of extra variables, without a Map.
Examples
Example 1
- Input
- prices = [1, 3, 4, 5, 9], budget = 10
- Output
- [0, 4]
1 + 9 = 10.
Example 2
- Input
- prices = [2, 5, 7, 11, 15], budget = 12
- Output
- [1, 2]
5 + 7 = 12.
Example 3
- Input
- prices = [-4, 0, 3, 8], budget = -1
- Output
- [0, 2]
Prices can be negative: -4 + 3 = -1.
Rules
pricesis sorted from smallest to largest, and has between 2 and 100,000 items.- There is always exactly one pair that works.
- Return
[smaller position, larger position].
Words on this page, in plain English (5)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- Map
- A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
- Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
This is Pair to target with one change: the prices are sorted. The Map solution still works. But sorted data is a gift, and this problem is about using it.
2. Solve an example by hand
prices = [1, 2, 3, 4, 50, 60], budget = 7. Try the cheapest and the dearest: 1 + 60 = 61, far too much. Is 60 ever useful? Its smallest possible partner is 1, and even that's too much. So 60 is out. Next: 1 + 50 = 51, still too much, so 50 is out too. 1 + 4 = 5, now too little. Is 1 ever useful? Its biggest remaining partner is 4, and that's not enough. So 1 is out. 2 + 4 = 6, too little, 2 is out. 3 + 4 = 7. Found it.
Every comparison crossed one item off for good.
3. The Map way
The Map solution from Pair to target passes here too: O(n) time, but O(n) extra memory for the Map. Can we keep the speed and drop the memory?
4. Spot the pattern
Sorted list, looking for a pair: the signal for two pointers from both ends. Sorting gives us the rule for which pointer to move.
5. The two-pointer idea
Keep left on the smallest remaining price and right on the largest. Add them:
- Equal to the budget? Done.
- Too small?
prices[left]can't be in the answer: its biggest possible partner isprices[right], and that's not enough. Moveleftup. - Too big?
prices[right]can't be in the answer: its smallest possible partner isprices[left], and that's already too much. Moverightdown.
Squeeze in from both ends
prices
- budget =
- 7
- sum =
- –
function sortedPair(prices, budget) { let left = 0; let right = prices.length - 1; while (left < right) { const sum = prices[left] + prices[right]; if (sum === budget) { return [left, right]; } else if (sum < budget) { left++; // need a bigger sum } else { right--; // need a smaller sum } }}Start with the cheapest item (left) and the most expensive (right).
6. The code, line by line
let left = 0; let right = prices.length - 1;Pointers at the cheapest and the most expensive item.
while (left < right) { const sum = prices[left] + prices[right];While there are two different items left to try, add their prices.
if (sum === budget) { return [left, right];Exactly the budget: return both positions.
leftis always smaller thanright, so they come out in the right order.} else if (sum < budget) { left++; // need a bigger sumToo small: the only way to grow the sum is a bigger left price.
} else { right--; // need a smaller sum }Too big: shrink it with a smaller right price.
The problem promises an answer, so the loop always returns before the pointers meet.
7. How fast is it?
| Every pair | Map | Two pointers | |
|---|---|---|---|
| Time | O(n²) | O(n) | O(n) |
| Extra memory | O(1) | O(n) | O(1) |
Two pointers get the best of both.
Common mistakes
- Moving the wrong pointer. Too small means you need more, which means moving
left(to bigger numbers). - Using this on an unsorted list. The whole argument ("its biggest possible partner is
prices[right]") depends on sorting.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Pair in a sorted list
Read the 14 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function sortedPair(prices, budget) { let left = 0; let right = prices.length - 1; while (left < right) { const sum = prices[left] + prices[right]; if (sum === budget) { return [left, right]; } else if (sum < budget) { left++; // need a bigger sum } else { right--; // need a smaller sum } }}