Seven problems where the key becomes an index. The move: turn the key into a bucket number, so an item finds its place by arithmetic and no comparison is needed.
You work on the back end of an ad platform, a payments app, a chat app, a social app, a streaming app, a bank and a store. Seven problems on this street come from them. Each one orders, ranks or compares items, and each key is small enough to use as a position.
When the key is a number in a known range, an item can go straight to its place. No item is compared with another. A sort of 100,000 values takes about 1,660,964 comparisons, and counting values between 0 and 10,000 takes 110,001 steps.
| Problem | The key | The index |
|---|---|---|
| Relative ranks in a contest | the score, at most 1,000,000 | a table with one cell for each score |
| Array partition for the best pair sum | the amount, at most 10,000 | a count for each amount |
| Sort characters by frequency | how often a letter appears | a bucket for each count |
| Top frequent words in a feed | how often a word appears | the count, found with a map |
| Bucket the sessions by length | minutes divided by 15 | one of 41 buckets |
| Contains nearby almost duplicate | the amount divided by t + 1 | a bucket in a window map |
| Largest gap using buckets | the price minus the minimum, divided by a width | a bucket that keeps its smallest and largest |
Here is the last row, the one that looks least like counting. The width of a bucket comes from the data.
Exercise · Predict the output: Which bucket for each price. The code finds the lowest and highest price. It sets the bucket width to the highest minus the lowest, divided by one less than the number of prices. What does it print?
prices = [1, 100, 7, 55, 30]
lo = min(prices)
hi = max(prices)
size = max(1, (hi - lo) // (len(prices) - 1))
print(*[(p - lo) // size for p in prices])The move has three steps, and you take them before you write code.
First, name the key. Second, write the formula that turns it into a whole number from 0 up to a known limit. The key itself, a count or the key divided by a width will do. Third, check that the limit is smaller than the work of a sort.
Once every key is a bucket number, items in different buckets are already in order, and only items in the same bucket need more work, often none. A pass over the buckets in order replaces the sort.
The check in the third step matters. Counting 100,000 amounts between 0 and 10,000 takes 110,001 steps. The relative ranks problem has scores up to 1,000,000, so its table takes 1,100,001 steps, which is still below 1,660,964. A range of 1,000,000,000 would need 1,000,000,001 cells, and a sort wins.
The frequency problem shows a count used as a key. Count each letter once, then walk the counts from the largest down to 1. For each count, write out the letters that have it, in alphabetical order.
A count can be the key: count each letter once, then walk the counts from the largest down and write the letters in alphabetical order.
Exercise · Put it in order: Letters by how often they appear. Arrange the lines into a function that writes each letter as many times as it appears, the most frequent letter first. Letters with the same count go in alphabetical order.
def sort_letters_by_frequency(text):
counts = [0] * 26
parts = []
for ch in text:
counts[ord(ch) - ord("a")] += 1
for c in range(len(text), 0, -1):
for letter in range(26):
if counts[letter] == c:
parts.append(chr(ord("a") + letter) * c)
return "".join(parts)
for letter in range(25, -1, -1):
for c in range(1, len(text) + 1):The Academy lesson Counting sort and stability counts values, computes start places and sorts digit by digit.
The comparison model shows why a sort that compares cannot beat n log n. Counting and grouping counts items under a computed key. This street does not teach those again. It changes three things about them.
The key is derived. A count is a key, and counts never pass the number of items. A value divided by t + 1 is a key: two amounts in one bucket differ by at most t.
A value measured from the minimum and divided by (highest - lowest) // (n - 1) is a key too. The width is chosen so that the largest gap cannot hide inside a bucket.
Buckets stay unsorted. For the largest gap, each bucket keeps only its smallest and largest price, because the answer lies between buckets. In the nearby-duplicate problem, one amount per bucket is enough: a second amount in the same bucket is already a match.
The arithmetic has edges. Floor division behaves differently for negative numbers in four languages. Rounding a bucket number up instead of down moves values into the wrong bucket.
The first edge is the one that breaks the nearby-duplicate problem, because bank entries can be negative. With a width of 2, the amounts -1 and 1 differ by 2. Truncating division puts both in bucket 0, and floor division puts -1 in bucket -1.
Truncating division sends -1 and 1 to bucket 0 when the width is 2. Use floor division so every bucket has the same width.
Exercise · Find the bug: The bucket of a negative amount. This looks for two entries at most k places apart whose amounts differ by at most t. It puts each amount in a bucket of width t + 1 and keeps the entries of the last k places. It is right for positive amounts. Which line is wrong?
def has_near_duplicate(amounts, k, t):
width = t + 1
def bucket(x):
return int(x / width)
window = {}
for i, x in enumerate(amounts):
b = bucket(x)
if b in window:
return True
if b - 1 in window and x - window[b - 1] <= t:
return True
if b + 1 in window and window[b + 1] - x <= t:
return True
window[b] = x
if i >= k:
del window[bucket(amounts[i - k])]
return FalseThe second edge is a bucket number that is rounded up. The next block shows how that reorders sessions.
Exercise · Break it: A bucket number rounded up. This code groups sessions into buckets of 15 minutes and lists the session indexes bucket by bucket, in input order inside a bucket. It computes the bucket as (minutes + 14) / 15. Find an input where it gives the wrong order.
def order_sessions_by_bucket(lengths):
counts = [0] * 41
for x in lengths:
counts[(x + 14) // 15] += 1
start = [0] * 41
for b in range(1, 41):
start[b] = start[b - 1] + counts[b - 1]
result = [0] * len(lengths)
for i, x in enumerate(lengths):
b = (x + 14) // 15
result[start[b]] = i
start[b] += 1
return resultSolve them in this order. The first two index by the value itself, and the next three index by a count or a bucket of minutes. The last two compute a width from the data.
Before you code each problem, write two lines: the key and the formula that turns it into an index, and the size of the table. If the table is larger than the work of a sort, choose another tool.
Give each problem about 20 minutes. Spend the first four on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Four edge cases come back on most rungs. A list can be empty or hold one item, and all keys can be equal. A key can be negative, and a bucket can be empty between two full ones. Write one small test for each.
When a solution fails, check the formula first. Most wrong answers on this street have one of three causes. A division rounds the wrong way, a table is one cell too small, or an empty bucket was skipped.
Checkpoint · Counting and buckets
Q1/5 A list holds 100,000 amounts, each between 0 and 10,000. About how many steps does counting take, and how many comparisons does a sort take?
Answer: B
Counting reads each amount once and then walks 10,001 counts: 100,000 + 10,001 = 110,001. A sort that compares needs about n log2 n, which is 1,660,964 for 100,000 values.
Q2/5 The text is "mississippi". Letters are written out as often as they appear, the most frequent first, and ties go in alphabetical order. What is the result?
Answer: B
The letters i and s both appear 4 times, so i comes first. The letter p appears twice and m once.
Q3/5 The prices 1, 100, 7, 55 and 30 go into buckets of width 24, which is (100 - 1) // 4. Why can the largest gap not hide inside one bucket?
Answer: B
The 5 prices have 4 gaps that add up to 99, so the largest gap is at least 24.75, which rounds up to 25. Two prices in a bucket of width 24 differ by at most 23, and the answer is found between buckets.
Q4/5 With a width of 2, which buckets do the amounts -1 and 1 belong to when the division is a floor division?
Answer: B
Floor division gives -1 // 2 = -1 and 1 // 2 = 0. Truncating division gives 0 for both, and then two amounts that differ by 2 look as if they are within t = 1.
Q5/5 A list holds 100,000 values, and each value can be as large as 1,000,000,000. Is a counting table a good plan?
Answer: C
A table must be smaller than the work it saves. With this range, a sort wins by a wide margin.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.