Three scheduling problems with a clock. The move: keep a heap of what is ready and a heap of what is busy, and move items between them before every decision.
You work on an ad server, a clinic booking page and a charging network. Each one assigns work to resources that are used for a while and then return. Which item is ready, and when does a busy one come back?
Every problem on this street answers both questions with two heaps. Here is what each one holds.
| Problem | The ready heap | The busy heap |
|---|---|---|
| Schedule tasks with cooldown | campaigns, by most ads left | campaigns, by the tick they may show again |
| Meeting rooms with a heap | free room numbers, lowest first | rooms, by the minute they are free again |
| Busiest meeting room | free bay numbers, lowest first | bays, by the end of their current stay |
The ready heap is ordered by the rule of the problem. The busy heap is always ordered by time.
Exercise · Predict the output: The last tick of each campaign. Campaign 0 has 3 ads and rests 1 tick after each ad. Campaign 1 has 2 ads and rests 2 ticks. In each tick the ready campaign with the most ads left shows, and the smaller index wins a tie. What does the code print?
import heapq
counts = [3, 2]
cooldowns = [1, 2]
ready = [(-c, i) for i, c in enumerate(counts)]
heapq.heapify(ready)
resting = []
tick = 1
last = [0, 0]
while ready or resting:
while resting and resting[0][0] <= tick:
_, left, i = heapq.heappop(resting)
heapq.heappush(ready, (-left, i))
if ready:
left, i = heapq.heappop(ready)
left = -left - 1
last[i] = tick
if left > 0:
heapq.heappush(resting, (tick + cooldowns[i] + 1, left, i))
tick += 1
print(*last)Write two lines before you code: what is ready and in what order, and when does a busy item return. Then the loop has the same shape on every rung.
Before each decision, every busy item whose time is at most the clock has moved into the ready heap. The busy heap holds only later items, and the decision takes the top of the ready heap.
When the ready heap is empty, do not step the clock one tick at a time. Jump it to the earliest return time, the top of the busy heap. A single campaign with 200,000 ads and a rest of 10,000 ticks ends at tick 2,000,190,000. Stepping reaches that tick in 2,000,190,000 steps, and the jump takes one step for each ad.
Move due items to the ready heap. If nothing is ready, jump the clock to the earliest return time.
Exercise · Put it in order: How many rooms at once. The appointments are sorted by start. A room that frees at the minute a new appointment starts can be reused. Arrange the lines to return the number of rooms in use at the busiest moment.
def rooms_needed(starts, ends):
busy = []
best = 0
for i in range(len(starts)):
if busy and busy[0] <= starts[i]:
heapq.heappop(busy)
heapq.heappush(busy, ends[i])
best = max(best, len(busy))
return best
if busy and busy[0] < starts[i]:The Academy lesson Scheduling with heaps shows the ready heap, the rest, the jump over idle time and a pool of workers. Heaps and priority queues gives the heap. This street changes three things.
The ready items are numbers. In the room problems, a heap of free room numbers hands out the lowest free room. With the appointments [0, 10], [5, 8], [9, 12], [13, 15] and [11, 20] and no gap, the rooms are 1, 2, 2, 2 and 1. With a gap of 2 minutes before a room can be reused, they are 1, 2, 3, 1 and 2.
The gap only moves the return time. A room is busy until the end plus the gap. Nothing else in the loop changes, and that is the point of the two-heap shape.
A request can wait and keep its length. In the bay problem, a request that finds every bay busy takes the first bay that frees, at that time. It then ends at that time plus its own length, not at its asked end time.
Take 2 bays and the requests starting at 1, 2, 3, 4 and 5, with asked ends at 2, 7, 6, 6 and 7. The right answer is bay 0, which serves 3 requests. Using the asked end time instead gives bay 1.
Queued requests add up. One bay, 100,000 requests, and a length of 10^9 each put the last end time at 100,000,000,000,000. A 32-bit integer holds at most 2,147,483,647, so store the times in 64 bits.
A request that waits for a bay ends at the time the bay frees plus its own length, not at the end it asked for.
Exercise · Find the bug: A request that waits. Starts are in increasing order. A request takes the free bay with the smallest number. If every bay is busy, it takes the bay that frees first and keeps its length. The function returns the bay that served most requests. Which line is wrong?
import heapq
def busiest_bay(bays, starts, ends):
free = list(range(bays))
heapq.heapify(free)
busy = []
served = [0] * bays
for i in range(len(starts)):
while busy and busy[0][0] <= starts[i]:
heapq.heappush(free, heapq.heappop(busy)[1])
finish = ends[i]
if free:
bay = heapq.heappop(free)
else:
freed_at, bay = heapq.heappop(busy)
finish = ends[i]
heapq.heappush(busy, (finish, bay))
served[bay] += 1
return served.index(max(served))Solve them in this order. The first adds a cooldown, the second adds room numbers and a gap, and the third makes requests wait.
Before you code each problem, write two lines: what is ready and in what order, and when a busy item returns. If you can say both in one sentence each, the loop writes itself.
Give each problem about 30 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 nothing ready at the start, two items returning at the same moment, ties between ready items, and times past 32 bits. Write one small test for each.
When a solution fails, trace three steps by hand and print both heaps. Most wrong answers on this street return an item at the wrong time, by one step or by one gap.
Checkpoint · Scheduling with heaps
Q1/5 In a scheduling problem with a clock, how is the busy heap ordered?
Answer: B
The busy heap answers one question: which item returns next. Its top is the earliest return time, which is also the time to jump to when nothing is ready.
Q2/5 Nothing is ready, and the earliest busy item returns at tick 90,000 while the clock shows tick 10. What do you do?
Answer: B
Nothing can change before the earliest return time, so every tick in between is empty. Jumping skips them in one step.
Q3/5 A room is free at the minute another meeting ends, and a new meeting starts at that minute. Does the new meeting need another room?
Answer: B
The test is end <= start. Freeing only rooms that ended strictly earlier would count a touching pair as overlapping.
Q4/5 Which heap hands out the lowest-numbered free room?
Answer: B
The free rooms are numbers, and the rule says the smallest wins, so a min-heap of numbers gives the answer in O(log n).
Q5/5 Every bay is busy. The first bay frees at time 20, and the request is 7 long. When does the request end?
Answer: B
The request starts when the bay frees and keeps its length, so it ends at 20 + 7 = 27.
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.