Arrays and hashing · Problem 1 of 3

Two gifts that use the whole budget

Pattern: Two Sum in O(n) with a Hash Map

easyNot solved yet

The problem

You're buying two gifts from a shop's price list and want to spend your budget exactly. Write a function that takes a list of whole-number prices and a budget, and returns the positions [i, j] (with i < j) of two different items whose prices add up to budget.

If more than one pair works, return the one you'd spot first reading the list left to right: the pair with the smallest j, and for that j, the smallest i. If no pair works, return an empty list.

text
1gift_pair([12, 30, 7, 18, 25], 37)  ->  [1, 2]
2gift_pair([5, 5, 10], 10)           ->  [0, 1]
3gift_pair([4, 9, 2], 8)             ->  []
Example 1
12
0
30
1
7
2
18
3
25
4

prices[1] + prices[2] = 30 + 7 = 37, so the answer is [1, 2].

In the first example, 30 + 7 = 37. In the second, two different items can have the same price. In the third, 4 + 4 would mean buying the same item twice, so there's no answer.

Write gift_pair(prices, budget) in Python or giftPair(prices, budget) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 20 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.