Problems where the sort rule is the hard part. The move: write the rule as a list of keys with directions and a tie rule, then ask what the sorted list lets you do next.
You work on the back end of a depot, a ride app, a chat app, a platform team and a social app. The problems on this street come from them. In each one, calling the sort takes one line. The work is deciding what to sort by.
A sort rule is a list of keys. The first key decides every pair it can, the second key decides the rest, and so on. A rule is complete when some key decides every pair.
| Problem | The order you build | Then the sorted list lets you |
|---|---|---|
| Largest perimeter from three sticks | lengths, largest first | check three neighbours |
| Custom sort of status codes | place in the given order, then alphabet | write the letters out |
| Sort the log lines by key | kind, then body, then identifier | leave one kind in input order |
| Reconstruct the queue by height | height descending, then count ascending | insert each person at their count |
| Order tasks by deadline and reward | deadline ascending | keep the best rewards in a heap |
Read the third column. The sort rarely gives the answer. It sets up a simple second step.
Here is the fourth row as code. Sort the people tallest first, with the smaller count first among equal heights, then insert each person at the position equal to their count.
Exercise · Predict the output: Rebuilding the photo line. Each person is [height, count], where the count is how many people in front are at least as tall. The code sorts them and inserts each height at the position given by the count. What does it print?
people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
people.sort(key=lambda p: (-p[0], p[1]))
line = []
for height, k in people:
line.insert(k, height)
print(*line)The move has three steps, and you take them before you write code.
First, list the keys in priority order, each with a direction. Second, say what happens to two items that match on every key: they keep their input order if the sort is stable, or they are interchangeable. Third, ask what the sorted list lets you do next: a scan, an insert, a group or a heap.
A sort order is a list of keys, each with a direction. The first key on which two items differ decides their order, so the rule is complete when some key, or the input order, decides every pair.
In the status codes, the first key is the rank of the letter in the given order. The second key is the letter itself. A letter missing from the order needs a rank too, and it should be larger than every rank in the order.
In the log lines, the first key is the kind: text before numeric. Text lines then sort by body and by identifier. Numeric lines have no key at all, and a stable sort keeps their input order.
Write the sort rule as a list of keys with directions and a tie rule before you code, then name what the order lets you do.
The perimeter problem shows the third step. After sorting the lengths, a strap that fails with the two straps directly below it fails with every smaller pair. So you scan from the largest down and check three neighbours. Three straps of 1,000,000,000 give 3,000,000,000, which is more than the 32-bit limit of 2,147,483,647.
Exercise · Find the bug: The flat brace. This sorts the strap lengths, then scans from the largest down. It returns the perimeter of the first three that can form a brace. A brace needs the two shorter straps to be longer than the longest. Which line is wrong?
def largest_frame_perimeter(straps):
straps.sort()
for i in range(len(straps) - 1, 1, -1):
shorter = straps[i - 1] + straps[i - 2]
if straps[i] <= shorter:
return shorter + straps[i]
return 0The Academy lesson Comparators in four languages shows the syntax of a key, of two stable passes and of a comparator. Counting sort and stability explains what a stable sort keeps. This street does not teach those again. It changes three things about them.
The key is computed from the data. The rank of a letter comes from a given order, and a letter that is not in it still needs a rank. The tempting tool is a search that returns -1 for a missing letter, and -1 sorts before every real rank.
A search for a letter's place returns -1 when it is missing, and -1 sorts first. Give missing letters a rank after the order.
The sort is the setup. After tallest first, each insert at the person's count lands correctly, because a shorter person never changes how many taller people stand in front. The sorted list is not the answer, but it makes the answer one insert per person.
The size can be a trap. Checking every triple of 100,000 straps means 166,661,666,700,000 triples. One sort and one scan do the same work, and the perimeter needs 64 bits.
Exercise · Put it in order: Letters in the support team's order. Arrange the lines into a function that sorts the letters of a text by their place in a given order. Letters not in the order go last, in alphabetical order.
def sort_by_status_order(text, order):
rank = {}
for i, c in enumerate(order):
rank[c] = i
unknown = len(order)
letters = sorted(text, key=lambda c: (rank.get(c, unknown), c))
return "".join(letters)
unknown = -1
letters = sorted(text)The same idea fails in a different place. The next block returns to the queue, where the tie rule on equal heights decides everything.
Exercise · Break it: The wrong tie among equal heights. This code rebuilds the photo line: tallest first, and among equal heights the larger count first, then it inserts each person at their count. Find an input where the line is wrong.
def rebuild_the_line(people):
people.sort(key=lambda p: (-p[0], -p[1]))
line = []
for height, k in people:
line.insert(k, [height, k])
return lineSolve them in this order. The first two need a sort and a scan or a pairing, and the next two compute their keys.
The last two use the sorted list as the setup for an insert or a heap.
Before you code each problem, write the rule as a list: each key, its direction, and what a full tie does. Then write the one thing the sorted list lets you do next.
Give each problem about 20 minutes. Spend the first four on the rule and the next step, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Three edge cases come back on most rungs. Items can tie on every key, an item can be missing from a given order, and a total can pass 32 bits. Write one small test for each.
When a solution fails, check the rule first. Most wrong answers on this street come from a direction that is reversed, a tie that nobody decided, or a missing item that got the wrong rank.
Checkpoint · Custom orders
Q1/5 A sort rule is a list of keys. When is the rule complete?
Answer: B
The first key on which two items differ decides their order. If two items match on every key, the rule must say what happens: keep the input order, or treat them as the same.
Q2/5 The text is "abc" and the support team's order is "c". Letters missing from the order go last, alphabetically. What is the sorted text?
Answer: C
The letter c has rank 0. The letters a and b are missing, so they share a rank after it and are ordered alphabetically: c, a, b.
Q3/5 Three people have height 5 and counts 0, 1 and 2. After the tallest-first sort, which one is inserted first among them?
Answer: C
The smaller count stands further forward, so it is inserted first. Inserting the larger count first gives the counts 0, 2, 1 for the line.
Q4/5 The straps are 1, 2 and 3. What is the largest perimeter of a brace?
Answer: C
Two straps of 1 and 2 add up to exactly 3, so the brace would lie flat. The test is strict, so no triple works and the answer is 0.
Q5/5 Three straps are each 1,000,000,000 long. What is the perimeter, and does it fit in a 32-bit int?
Answer: B
The sum is 3,000,000,000, which is above 2,147,483,647. Use a 64-bit integer for the total.
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.