Five problems that do not need a full sort from scratch. The move: ask how much order the question needs, and combine the order you already have by comparing only fronts.
You work on the back end of a rides app, a maps app, a search engine, a bank and a monitoring tool. Five problems on this street come from them. Each one holds some order already, or needs only a part of the order.
A full sort from scratch ignores that order and spends more work than the question needs. For 100,000 values, a full sort takes about 1,660,964 comparisons. This street shows five cases that need less.
| Problem | The order you have, or need | What you buy |
|---|---|---|
| Sort a list of nearly sorted values | every value is within k places of home | a heap of k + 1 values |
| Sort a stream of nearly sorted chunks | sorted runs side by side | merging neighbouring runs |
| Largest values from many shards | each shard is sorted | a heap with one front per shard |
| Wiggle sort the readings | only the two halves by rank | a sort, or a partition at the median |
| Count of range sums in a window | halves that merge sort has just ordered | two pointers across the halves |
Read the last column. In every row you compare fronts, or you compare a rank, and you never compare everything with everything.
Here is the third row on three small shards. At each step the code looks at the front of every shard and takes the best one.
Exercise · Predict the output: Which fronts win. Each shard is sorted from the best score to the worst. The code takes the best front score five times. After that, how many scores has it taken from each shard?
shards = [[50, 30, 10], [45, 44], [48, 20, 5]]
k = 5
fronts = [0, 0, 0]
taken = 0
while taken < k:
best = -1
for s in range(3):
if fronts[s] < len(shards[s]) and (best == -1 or shards[s][fronts[s]] > shards[best][fronts[best]]):
best = s
fronts[best] += 1
taken += 1
print(*fronts)The move has three steps, and you take them before you write code.
First, ask what the question needs: the full order, the first k values, or only a split by rank. Second, ask what order the input already has. Third, combine what you have by comparing only fronts, and use a heap when there are many fronts.
Two ordered lists merge by comparing only their fronts, and many ordered lists merge with a heap of their fronts. So combine the order you already hold, and spend work only on what the question asks for.
A list whose values are at most k places from home shows the idea. The value that belongs first is among the first k + 1 values. So a heap of the first k + 1 values gives the first output, and each new value read lets you write one more.
For 100,000 values with k = 10, a full sort takes about 1,660,964 comparisons. A heap of 11 values costs about 345,943 steps, which is 100,000 values times log base 2 of 11.
The runs problem uses the same idea from another side. A stream of sorted stretches needs one pass to find the runs, then merges of neighbours. With 8 runs there are 3 rounds, and each round touches every value once. For 100,000 values that is 300,000 moves.
When every value is at most k places from home, a heap of k plus one values always holds the next output.
Exercise · Find the bug: The window one value too small. Every value in this list is at most k places from its place in the sorted order. The code keeps a heap and writes the smallest value out when the heap is large enough. Which line is wrong?
def sort_nearly_sorted(values, k):
import heapq
heap = []
result = []
for v in values:
heapq.heappush(heap, v)
if len(heap) >= k:
result.append(heapq.heappop(heap))
while heap:
result.append(heapq.heappop(heap))
return resultThe Academy lesson Merge sort and inversions merges two halves and counts pairs while merging. Quick sort partitions around a pivot, and Simple sorts shows how insertion sort uses nearly sorted input.
Heaps and priority queues and Top k and k-way merge build the heap. This street does not teach those again. It changes three things about them.
The input is not a blank list. The order that exists decides the tool: a heap of k + 1 values, merges of neighbouring runs, or one front per shard. For 5,000 shards of 100,000 scores each, there are 500,000,000 scores in all. A page of 100,000 results needs only 100,000 pops of a heap of 5,000 fronts, about 1,228,771 steps.
You may need only the split. The wiggle problem needs the lower half and the upper half by rank, and not their full order. A sort gives both halves at once, and a partition around the median can find them in linear time on average. Each half is then filled from its largest value, so equal readings from the two halves end up apart.
Fill each half from its largest value. From the smallest, the median can end up next to itself.
The merge can count. In the range-sum problem, the prefix sums of two halves are sorted, and a pair counts when its difference lies in a band. Two pointers across the sorted right half give the count for each left value, and the count is added before the halves are merged.
Exercise · Put it in order: Counting across two sorted halves. Arrange the lines into a function that counts the pairs (a from left, b from right) with low <= b - a <= high. Both lists are sorted from smallest to largest.
def count_cross(left, right, low, high):
count = 0
lo = 0
hi = 0
for a in left:
while lo < len(right) and right[lo] - a < low:
lo += 1
while hi < len(right) and right[hi] - a <= high:
hi += 1
count += hi - lo
return count
while hi < len(right) and right[hi] - a < high:
count += hi - lo + 1The wiggle problem has a trap in how the halves are filled. The next block shows what happens when each half is filled from its smallest value.
Exercise · Break it: Filling the halves from the smallest. This code sorts the readings, puts the lower half into the even places and the upper half into the odd places, and fills each half from its smallest value. The result must zigzag with no equal neighbours. Find an input where it fails.
def wiggle_arrange(readings):
ordered = sorted(readings)
n = len(ordered)
half = (n + 1) // 2
result = [0] * n
for i in range(n):
result[i] = ordered[i // 2] if i % 2 == 0 else ordered[half + i // 2]
return resultSolve them in this order. The first three merge or heap what is already ordered, the fourth needs only a split by rank, and the last counts while merging.
Before you code each problem, write two lines: what order the question needs, and what order the input already has. The gap between them is the work you must buy.
Give each problem about 25 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. An input can be empty or already sorted, k can be zero or larger than the list, a shard can be empty, and counts can pass 32 bits. Write one small test for each.
When a solution fails, check the two lines first. Most wrong answers on this street have one of three causes.
The window is one too small, a pointer test is one too strict, or a half is filled from the wrong end.
Checkpoint · Selection and merging
Q1/5 Every value is at most 2 places from its place in the sorted order. How many values must the heap hold before the first value is written out?
Answer: B
The value that belongs first is among the first k + 1 values, which is 3 values for k = 2. Writing at size 2 is one value too early.
Q2/5 You merge many sorted shards to get the best k scores. What does the heap hold at any moment?
Answer: C
Pop the best front, then push the next score of the same shard. The heap never holds more values than there are shards, and you stop after k pops.
Q3/5 A stream of 100,000 values splits into 8 sorted runs. Merging neighbouring runs in rounds takes how many rounds?
Answer: C
Each round halves the number of runs: 8, 4, 2, 1. That is 3 rounds, and each round touches every value once, so 300,000 moves for 100,000 values.
Q4/5 The readings are 4, 5, 5, 6. Each half of the sorted list is filled from its largest value, the lower half into the even places and the upper half into the odd places. What is the result?
Answer: B
The lower half is 4, 5 and the upper half is 5, 6. Filling each from its largest gives 5, 6, 4, 5. Filling each from its smallest gives 4, 5, 5, 6, which has equal neighbours.
Q5/5 The left half is 0, 2 and the right half is -1, 3, 4. How many pairs (a, b) have 1 <= b - a <= 4?
Answer: C
The pairs are 0 and 3, 0 and 4, 2 and 3, and 2 and 4. The value -1 never reaches the band. Two pointers over the sorted right half find them without checking every pair.
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.