Three problems where you write the heap yourself, on one array. The move: sift down from the last parent to the first, and grow the finished part at the back.
You work on a listing site, a payments app and an event log. Until now you have used a ready-made heap. In these problems you work on the heap array yourself, or you size the heap carefully, so that the cost stays low.
Each problem uses a different part of the machinery. Here is what each one asks of the array.
| Problem | What the array holds | The operation that matters |
|---|---|---|
| Build a heap in linear time | all prices at once | sift down every parent, from the last one |
| Heap sort in place | the heap at the front, the finished part at the back | move the root to the end, shrink the heap, repair |
| Sort a nearly sorted stream | a window of k + 1 events | push the new event, then release the smallest |
The parent of cell i is cell (i - 1) // 2, and its children are cells 2i + 1 and 2i + 2. The tree is only index arithmetic, and the Academy lesson Heaps and priority queues built it step by step.
Exercise · Predict the output: Two steps of heap sort. The array is a min-heap. Each step swaps the root with the last cell of the heap part, shrinks the heap to `end` cells, and sifts the new root down. What does the code print after the two steps?
values = [1, 4, 3, 9, 8, 7]
for end in [5, 4]:
values[0], values[end] = values[end], values[0]
i = 0
while True:
smallest = i
left, right = 2 * i + 1, 2 * i + 2
if left < end and values[left] < values[smallest]:
smallest = left
if right < end and values[right] < values[smallest]:
smallest = right
if smallest == i:
break
values[i], values[smallest] = values[smallest], values[i]
i = smallest
print(*values)All three problems rest on one operation, sift-down. Compare a cell with its children, and swap it with the smaller child if that child is smaller. Repeat from the child's cell. The move is about where you start and in what order.
When you sift down from cell i, the subtrees below i are already heaps, so one sift-down makes the subtree at i a heap. Start at the last parent, at index n // 2 - 1, and go back to index 0.
Leaves are heaps already, so the work starts at the last parent. A parent near the bottom has little room to fall, and only the few cells near the top can fall far. That is why the build takes about 2n steps, not n log n.
The numbers show it. For 100,000 random values, the bottom-up build makes 74,756 swaps, and pushing the values one at a time makes 128,670. For 100,000 descending values, the pushes make 1,468,946 swaps, and the build makes 99,990.
Build a heap by sifting down every parent, from the last parent back to the root.
Exercise · Put it in order: Sift a cell down. The cell i may be larger than its children. Arrange the lines to sift it down in a min-heap until it is no larger than both children, and return the array.
def sift_down(values, i):
while True:
smallest = i
left, right = 2 * i + 1, 2 * i + 2
if left < len(values) and values[left] < values[smallest]:
smallest = left
if right < len(values) and values[right] < values[smallest]:
smallest = right
if smallest == i:
return values
values[i], values[smallest] = values[smallest], values[i]
i = smallest
if right < len(values) and values[right] < values[i]:The Academy lesson Heaps and priority queues builds the heap, with push, pop and heapify. This street changes three things.
You choose the order of the build. Sifting down from the top toward the bottom does not build a heap. For the values 2, 3, 4, 1 and 5, that order leaves 2, 1, 4, 3 and 5, and the parent 2 is larger than its child 1.
Go from the last parent back to the root. With the values 9, 4, 7, 1, 8 and 3, the bottom-up build makes 4 swaps and gives 1, 4, 3, 9, 8 and 7.
The array does double duty. To sort in place, keep the heap at the front and the finished part at the back. A min-heap puts the smallest value at the root, and each step moves it to the back.
The array therefore ends in descending order. For the amounts 5, -2, 9, 9 and 0, the result is 9, 9, 5, 0 and -2.
The heap can stay small. If every event is at most k places from its sorted place, a heap of k + 1 events is enough. Push the new event, then release the smallest, because no event still to come can be smaller than it.
For the arrival order 2, 1, 4, 3, 6 and 5, with k = 1, the release order is 1, 2, 3, 4, 5 and 6. The heap never holds more than 2 events, however long the stream is.
Release only after the new event joins the heap. Releasing first can send out an event that is not the smallest.
Exercise · Find the bug: Released too early. Every event is at most k places from its sorted place. The first k events wait in a min-heap. Each later event should join the heap, and then the smallest is released. Which line is wrong?
import heapq
def release_in_order(events, k):
heap = events[:k]
heapq.heapify(heap)
released = []
for x in events[k:]:
released.append(heapq.heapreplace(heap, x))
while heap:
released.append(heapq.heappop(heap))
return releasedSolve them in this order. The first builds the heap in one pass. The second reuses the array for the sort. The third keeps a heap of exactly k + 1 values.
Before you code each problem, write two lines: where the work starts in the array, and which cells are the heap at each step. If you can draw the array with a dividing line, the loop follows.
Give each problem about 25 minutes. Spend the first five on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases.
Four cases come back on every rung. They are a single value, two equal values, values already sorted in reverse, and k equal to 0. Write one small test for each.
When a solution fails, check the boundary first: the last parent, the first cell past the heap part, and k + 1 against k.
Checkpoint · Heaps from scratch
Q1/5 A heap of n values lives in an array. Where is the last parent, and in which order do you sift down to build the heap?
Answer: B
The cells from n // 2 onward are leaves, and a leaf is already a heap. Going back from the last parent means every sift-down starts below subtrees that are ready.
Q2/5 Sifting down from index 0 forward does not build a heap. What is wrong with it?
Answer: B
The subtrees must be heaps before you sift above them. For 2, 3, 4, 1 and 5 the forward order leaves a parent of 2 above a child of 1.
Q3/5 Why does the bottom-up build take about 2n steps, not n log n?
Answer: B
Half of the cells are leaves and do not move. A quarter can fall at most one level, an eighth at most two, and so on, so the total is about 2n.
Q4/5 A min-heap sorts an array in place. In which order does the array end up?
Answer: B
The root is the smallest, and it goes to the end of the heap part. The next smallest goes before it, so the array reads from the largest to the smallest.
Q5/5 Every event is at most 3 places from its sorted place. How many events does the heap hold when you release one?
Answer: B
The heap holds k + 1 events, which is 4 here. The new event may be the smallest, so it must be in the heap before the release.
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.