Gift Pair
You have a gift card worth exactly card, and a list prices of item prices. Exactly one pair of different items has prices that add up to card.
Write gift_pair(prices, card) that returns the positions of the two items as a list [i, j] with i < j.
Understand the problem
Check the rules on small examples.
Prices are [3, 2, 4] and the card is 6. Which positions are the answer?
[0, 0][1, 2][0, 2]
The two items must be different items. [0, 0] would use the 3 twice (3 + 3 = 6), which is not allowed. The pair 2 + 4 = 6 sits at positions 1 and 2.
Prices are [3, 3] and the card is 6. What is the answer? Type it like [0, 1].
Two different items can have the same price. Positions 0 and 1 are different items, so [0, 1] is right. Equal prices are an edge case to remember.
Try examples by hand
Count how much work the obvious approach is.
How many pairs of different items can you form from 5 prices? (Each pair counted once.)
The pairs are positions (0,1) (0,2) (0,3) (0,4) (1,2) (1,3) (1,4) (2,3) (2,4) (3,4): that is 4 + 3 + 2 + 1 = 10. For n items the number is n x (n - 1) / 2.
About how many pairs are there among 1000 prices?
- About 1,000
- About 500,000
- About 1,000,000,000
1000 x 999 / 2 = 499,500, roughly half a million. The number of pairs grows with the square of the list length: 10 times more prices means about 100 times more pairs.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def gift_pair(prices, card):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
How can you be sure you have looked at every pair of different items, with no pair counted twice?
Hint 2: the shape of the answer
Two loops. The outer loop picks the first position i. The inner loop picks a later position j. Check whether the two prices add up to card.
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
Take one price p. What exactly are you searching the rest of the list for?
- Any number smaller than
p - The number
card - p - The largest number
If p is one half of the pair, the other half must be exactly card - p. You are not searching for "something that works"; you are searching for one specific number.
Looking for a number in a list means checking items one by one. Which Python structure can find a key in about the same time however big it is?
- A list
- A dictionary (or set)
- A tuple
A dictionary uses hashing: it turns the key into a position, so a lookup takes about the same time for 10 keys or 10 million. That is the trick of this whole chapter.
You walk through the prices once, at position j with price p, and keep a dictionary seen of earlier prices and their positions. What do you look up in seen?
pcard - pcard + p
You need an earlier item whose price is card - p. If it is in seen, its stored position and j are the answer. If not, store p and move on.
Make it faster
Now write the version that walks through the list once.
def gift_pair(prices, card):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
What do you wish you could do instantly, instead of searching the rest of the list?
Hint 2: the pattern
Remember what you have seen in a dictionary, so that "have I seen the number I need?" is one lookup.
Hint 3: pseudocode
seen = empty dictionary (price -> position)
for each position j and price p:
if (card - p) is a key of seen:
return [seen[card - p], j]
seen[p] = j
Think about why you look before you store.
Reflect
Brute force: O(n squared)
def gift_pair(prices, card):
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[i] + prices[j] == card:
return [i, j]
Improved: O(n)
def gift_pair(prices, card):
seen = {}
for j, price in enumerate(prices):
need = card - price
if need in seen:
return [seen[need], j]
seen[price] = j
Another way: build the table first, then look up
def gift_pair(prices, card):
position = {price: i for i, price in enumerate(prices)}
for i, price in enumerate(prices):
j = position.get(card - price)
if j is not None and j != i:
return [min(i, j), max(i, j)]
Pattern: replace a repeated search with a lookup table. The brute force searches the rest of the list for card - p, once per item. A dictionary answers "is this number here, and where?" in about one step. You trade memory (the dictionary) for time. Whenever you see "find an item that matches something about another item", ask whether a dictionary can answer the matching part.
Cost:
| Version | Time | Extra space |
|---|---|---|
| Every pair | O(n squared) | O(1) |
| Dictionary | O(n) | O(n) |
Why look before storing: if you store first, an item can find itself (3 and card 6 would match 3 + 3 with one item). Looking first guarantees the match is an earlier, different item.
What an interviewer might ask next: What if several pairs match and you must return all of them? What if the list is sorted: can you solve it with no dictionary at all (two pointers)?
import random
def SAME(got, want):
return sorted(got) == sorted(want)
VISIBLE = 3
CASES = [
(([2, 7, 11, 15], 9), [0, 1], 'a pair at the start'),
(([3, 2, 4], 6), [1, 2], 'one item must not be used twice'),
(([8, 1, 5, 9], 14), [2, 3], 'a pair at the end'),
(([3, 3], 6), [0, 1], 'two equal prices'),
(([-4, 1, 9, -1], 8), [2, 3], 'negative prices'),
(([0, 4, 3, 0], 0), [0, 3], 'a zero price'),
(([10, 20, 30, 40, 50], 90), [3, 4], 'a pair at the very end'),
(([5, 75, 25], 100), [1, 2], 'the first item is not used'),
]
def REFERENCE(prices, card):
seen = {}
for j, price in enumerate(prices):
if card - price in seen:
return [seen[card - price], j]
seen[price] = j
LIMIT = 2.0
def PERF():
cases = []
for n, seed in ((20000, 1), (60000, 2)):
while True:
values = random.Random(seed).sample(range(10 ** 9), n)
card = values[-1] + values[-2]
wanted = set(values)
pairs = sum(1 for v in values if card - v in wanted and card - v != v)
if pairs == 2: # each pair is seen from both sides: exactly one pair exists
break
seed += 100
cases.append(('%d prices' % n, (values, card)))
return cases