Pair to target
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.
You have a gift card worth exactly budget, and you want to spend all of it on two different items.
Given a list of item prices and the budget, return the positions of the two items whose prices add up to exactly budget.
Positions start at 0, so the first item is at position 0. You can return the two positions in either order.
Examples
Example 1
- Input
- prices = [3, 8, 5, 2], budget = 10
- Output
- [1, 3]
8 (position 1) + 2 (position 3) = 10.
Example 2
- Input
- prices = [4, 4], budget = 8
- Output
- [0, 1]
Two different items can have the same price.
Example 3
- Input
- prices = [1, 6, 9, 13], budget = 15
- Output
- [1, 2]
6 + 9 = 15.
Rules
- There is always exactly one pair of items that works.
- You can't pick the same item twice, but two different items may have the same price.
priceshas between 2 and 10,000 items. Prices can be negative or zero.
Words on this page, in plain English (2)Open if any word is new to you
- 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.
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
We get a list of prices and a budget. Somewhere in the list are two different items whose prices add up to exactly the budget. We return their positions, not the prices.
Positions trip people up at first: in [3, 8, 5, 2], the price 8 is at position 1, because counting starts at 0.
2. Solve an example by hand
Take prices = [3, 8, 5, 2] and budget = 10. Without code, you would probably do this: take the first price, 3, and look for a 7. There isn't one. Take 8 and look for a 2. There it is, at position 3. The answer is [1, 3].
Notice what you did in your head: for each price, you knew exactly which number you were looking for. That thought is the key to this problem.
3. The slow way: try every pair
The most direct program checks every pair of items: the first with every other, then the second with every later one, and so on.
The slow way: try every pair
prices
- budget =
- 10
- pairs checked =
- 1
Check #1: 3 + 8 = 11. Not 10, keep going.
function pairToTarget(prices, budget) { for (let i = 0; i < prices.length; i++) { for (let j = i + 1; j < prices.length; j++) { if (prices[i] + prices[j] === budget) return [i, j]; } }}This is correct, and writing it first is a good habit. But count the work: for n items there are about n × n ÷ 2 pairs. For 4 items that's 6 checks. For 10,000 items it's about 50 million. We call this O(n²) ("O of n squared"): double the list, and the work goes up four times.
4. Spot the pattern
Look back at step 2. For each price, we don't need to compare it with everything; we know the one partner it needs: budget - price. So the real question for each item is:
Have I already seen the partner I need?
"Have I seen this before?" is the signal for the hashing pattern. A Map can answer it instantly, no matter how many things it holds, because it finds a key directly instead of searching for it.
5. The faster idea
Walk through the prices once. For each one:
- Work out the partner it needs:
budget - price. - If the partner is already in the Map, we're done: return its position and the current one.
- Otherwise, store the current price and its position in the Map, and move on.
The fast way: remember what you've seen
prices
- budget =
- 10
- partner =
- –
seen (Set)
empty
function pairToTarget(prices, budget) { const seen = new Map(); // price → position where we saw it for (let i = 0; i < prices.length; i++) { const partner = budget - prices[i]; if (seen.has(partner)) { return [seen.get(partner), i]; } seen.set(prices[i], i); }}Start with an empty Map. It will remember every price we pass, and its position.
Why check before storing? Because the problem says we can't use the same item twice. If the budget is 6 and the price is 3, checking first means the 3 can't pair with itself; it can only pair with a different 3 found later.
6. The code, line by line
function pairToTarget(prices, budget) { const seen = new Map(); // price → position where we saw itCreate an empty Map called
seen. Its keys are prices; its values are the positions where we saw them.for (let i = 0; i < prices.length; i++) { const partner = budget - prices[i];Go through every position
i. Work out the partner price this item needs to reach the budget.if (seen.has(partner)) { return [seen.get(partner), i]; }seen.has(partner)asks the Map whether we have passed that price already. If so,seen.get(partner)gives its position, and we return both positions.seen.set(prices[i], i);No partner yet, so remember this price and where it was. A later item might need it.
7. How fast is it?
| Slow way (every pair) | Fast way (Map) | |
|---|---|---|
| Time | O(n²): about 50 million checks for 10,000 items | O(n): at most 10,000 steps |
| Extra memory | O(1): nothing extra | O(n): the Map can hold every price |
This trade, using some memory to save a lot of time, is the heart of the hashing pattern. You will see it again and again.
Common mistakes
- Returning prices instead of positions. Store the position as the Map's value, and return positions.
- Storing before checking. Then an item can pair with itself: with
[3, 4, 3]and a budget of6, you would wrongly return[0, 0]instead of[0, 2]. - Using
seen.get(partner)as the check. A position can be0, and0counts as false in anif. Useseen.has(partner)to ask "is it there?".
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 to target
Read the 10 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 pairToTarget(prices, budget) { const seen = new Map(); // price → position where we saw it for (let i = 0; i < prices.length; i++) { const partner = budget - prices[i]; if (seen.has(partner)) { return [seen.get(partner), i]; } seen.set(prices[i], i); }}