Schedule tasks with cooldowns, single workers and pools of servers, with heaps of what is ready and what is busy.
An online store has one packing station. Orders arrive during the day, and the packer takes the shortest waiting order first, so fewer customers wait long. Each time the packer is free, it asks one question: which waiting order is the shortest?
If no order is waiting, the packer asks a second question: when does the next order arrive? Everything in this lesson is a way to answer these two questions fast.
A supermarket has three tills and one line of customers. The next customer goes to a free till. If every till is busy, the line waits for the first till to finish.
The manager watches two things: who is waiting in line, and when each busy till will be free. The tills and their finish times are the busy heap, and the line is the ready heap.
Three tills and one line. The next customer goes to a free till, or waits for the first till to finish.
A ready heap holds only the items that can run now, with the best one on top. Shortest job first uses a min-heap of lengths. Fullest kind first uses a max-heap of counts.
Items that cannot run yet wait somewhere else, ordered by time: a queue of resting items, or a heap of busy workers by finish time. A clock moves from one event to the next, and does not tick through idle time. When the clock reaches an item's time, the item moves into the ready heap.
Step by step: The ready jobs, in an array. The animated player loads in your browser.
Predict what happens
Q Four orders wait, with packing times 4, 3, 1 and 2. They are in a min-heap. Which order does the packer take next?
Answer: C
A min-heap keeps the smallest packing time on top. The shortest order is the one with time 1, so it is taken first.
Push each item when it becomes ready, and pop the best one when the worker is free. The online store has four orders with packing times 4, 3, 1 and 2, arriving at times 1, 2, 3 and 4.
The packer starts order 0 at time 1, and it ends at time 5. By then orders 1, 2 and 3 all wait. The heap gives the shortest, order 2, then order 3, then order 1. The packing order is 0, 2, 3, 1.
Push each order when it arrives and pop the shortest when the packer is free. The packing times four, three, one, two come out as one, two, three.
Step by step: The shortest ready job comes off the top. The animated player loads in your browser.
Exercise · Predict the output: Which order is packed next?. Four orders arrive at times 2, 2, 3 and 9 and need 3, 1, 2 and 1 units to pack. The packer always takes the shortest order that has arrived, and the clock jumps over idle time. In what order are the orders (numbered from 0) packed?
import heapq
arrival = [2, 2, 3, 9]
packing = [3, 1, 2, 1]
ready = []
now = 0
j = 0
order = []
while j < 4 or ready:
if not ready and now < arrival[j]:
now = arrival[j]
while j < 4 and arrival[j] <= now:
heapq.heappush(ready, (packing[j], j))
j += 1
length, i = heapq.heappop(ready)
now += length
order.append(i)
print(*order)Predict what happens
Q A min-heap of waiting orders holds the packing times 3, 1 and 2. The packer takes the top. Then order 4, with time 1, arrives. Which time is on top now?
Answer: C
The packer took the time 1. Now the heap holds 3 and 2. The new order with time 1 is pushed and moves to the top, because 1 is the smallest.
Some items must rest after they run. A build worker runs jobs of two kinds, A and B, three of each, and the same kind needs 2 units of rest. Put each kind with jobs left in a ready heap by count.
After a kind runs, and has jobs left, it goes to a queue with the time it is ready again. At time 1 the kind A runs, and is ready again at time 4. When the clock reaches 4, A moves back to the ready heap.
The schedule is A, B, idle, A, B, idle, A, B: 8 time units, with two idle units.
At time 3 in the schedule above, both kinds rest, and the ready heap is empty. Do not tick one unit at a time. Jump the clock to the front of the queue, time 4, and count the idle unit.
Ticking looks harmless on 6 jobs. But with two kinds of 50,000 jobs and a rest of 100,000 units, the schedule has 4,999,950,001 time units, almost all idle. A jump costs one step for each job.
When nothing is ready, jump the clock to the next ready time. Ticking through idle time can cost billions of steps.
Exercise · Find the bug: The rest that is one unit too long. Each kind of job must rest for `rest` units after it runs. This code finds how long the whole schedule takes, but it reports a time that is too long. Which line is wrong?
import heapq
from collections import deque
def schedule_length(counts, rest):
ready = [-c for c in counts]
heapq.heapify(ready)
resting = deque()
now = 0
while ready or resting:
if not ready:
now = resting[0][0]
while resting and resting[0][0] <= now:
heapq.heappush(ready, resting.popleft()[1])
left = heapq.heappop(ready) + 1
now += 1
if left < 0:
resting.append((now + rest + 1, left))
return nowPredict what happens
Q The ready heap is empty. The first resting item is ready at time 40, and the clock is at 12. What do you do?
Answer: B
Nothing can run before time 40, so the clock can move there at once. The units from 12 to 40 are idle, and they cost no steps.
With several workers, keep two heaps. The free workers are ordered by weight and then by number. The busy workers are ordered by finish time. Before each job, release every busy worker whose finish time has come.
If no worker is free, the job waits. Set the clock to the first finish time and release again. Then the free worker with the smallest weight takes the job.
Take three servers with weights 5, 1 and 3, and jobs of lengths 4, 1, 2, 6, 2, 3 and 1, one arriving at each time unit. The servers chosen are 1, 2, 2, 0, 1, 2 and 1. At time 2, server 2 finishes exactly when job 2 arrives, so it is free for that job.
A pool of servers needs two heaps: free servers by weight, and busy servers by finish time. A server that finishes now is free now.
Step by step: The busy server that finishes first. The animated player loads in your browser.
Exercise · Break it: The server that finishes right now. Job j arrives at time j and goes to the free server with the smallest weight, then the smallest number. When every server is busy, the job waits for the first one to finish. This code releases a server only when its finish time is below the start time. Find an input where it gives the wrong answer or crashes.
import heapq
def assign_servers(weights, lengths):
free_servers = [(w, i) for i, w in enumerate(weights)]
heapq.heapify(free_servers)
busy = []
result = []
for j, length in enumerate(lengths):
start = j
if not free_servers:
start = max(start, busy[0][0])
while busy and busy[0][0] < start:
_, w, i = heapq.heappop(busy)
heapq.heappush(free_servers, (w, i))
w, i = heapq.heappop(free_servers)
result.append(i)
heapq.heappush(busy, (start + length, w, i))
return resultTo keep two equal items apart, hold the item used last outside the heap for one step. Take the best of the rest, then put the held item back and hold the new one.
For the artist codes a, a, b, b, c, this gives a, b, a, b, c. If an item is still held when the heap is empty, no order exists. The codes a, a, a, b give no order.
Predict what happens
Q You build a playlist from the codes a, a, b. The heap has a (2) and b (1). You take a. What must you do before you take the next code?
Answer: B
The same code must not play twice in a row. Holding a outside the heap for one slot makes the heap give b next. Then a goes back, and the playlist is a, b, a.
Here is a heap of ready jobs next to two plainer ways to find the next job.
| Operation | Heap of ready jobs | Sorted list | Unsorted list, scanned each time |
|---|---|---|---|
| Push a ready job | O(log n) | O(n): later jobs shift along | O(1) |
| Pop the best ready job | O(log n) | O(1) from the right end | O(n): scan for it |
| Peek at the best job | O(1) | O(1) | O(n) |
| Build the ready heap from n jobs (heapify) | O(n) | O(n log n): a sort | O(1) |
| Search for a given job | O(n): a heap has no search order | O(log n) | O(n) |
| Schedule n jobs in all | O(n log n) | O(n^2) | O(n^2) |
A heap wins when jobs keep arriving and you need the best one each time. A sorted list is better for finding a given job.
Now drive a heap yourself. A min-heap of packing times shows the ready jobs, and the same heap with finish times shows the busy servers.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the desk yourself. The lab gives you a JobDesk class that hands jobs to a pool of servers. You write six methods: add_server, submit, last_start, jobs_on, free_servers and next_free_time.
Four things to take care over:
submit handles the job at the later of its arrival and the clock. The clock never moves back.When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a ready heap when items keep arriving and a worker must pick the best one each time: the shortest job, the fullest queue, the cheapest free server. Add a queue or a second heap when items must rest or workers are busy.
It also fits any simulation of events in time order, where the clock jumps from one event to the next.
If every job is known at the start and only one order matters, sort once and go through the list. A heap helps when the choice changes as items arrive, rest or finish. For a fixed priority and no rests, a sort is simpler.
Stepping one time unit at a time is correct, but idle units can number in the billions. With two kinds of 50,000 jobs and a rest of 100,000 units, the schedule has 4,999,950,001 units. Jump the clock to the next ready time instead.
while remaining:
slot += 1 # one step for each idle unit
if not ready:
slot = resting[0][0] # one jumpA server that finishes at time t is free at time t. Treating it as busy sends the jobs to the wrong servers.
A server that finishes at time t is free at time t. If you release only servers with a finish time below t, the jobs go to other servers. For weights 5, 1 and 3 and jobs of lengths 4, 1, 2, 6, 2, 3 and 1, the right answer is [1, 2, 2, 0, 1, 2, 1], and this mistake gives [1, 2, 0, 2, 1, 0, 1].
while busy and busy[0][0] < now: # wrong: a finish at now is not released
while busy and busy[0][0] <= now: # rightThe ready heap must hold only the jobs that have arrived. If you take the shortest job overall, you start a job before its arrival. For the arrivals 1, 2, 3, 4 and the packing times 4, 3, 1, 2, this gives the order [2, 3, 1, 0], and the right order is [0, 2, 3, 1].
heapq.heappush(ready, (packing[i], i)) # for every i at the start: wrong
if arrival[i] <= now: heapq.heappush(...) # right: push when it arrivesWhen equal items must be apart, the item used last has to stay out of the heap for one step. Without that, the best item is taken again. For the codes a, a, b the result is aab, with two a in a row.
code = heapq.heappop(heap) # the code just used is still in the heap
held = code # right: hold it out, push it back after the next popA clock adds up durations. With 100,000 orders of 10^7 time units each, it reaches 10^12, far above the largest 32-bit int, which is about 2.147 billion. Use a 64-bit number for the clock and for finish times.
int now = 0; // overflows near 2.1 billion
long now = 0; // holds up to about 9 x 10^18Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Ready, resting and idle
Q1/4 A heap-based schedule answers two questions again and again. Which two?
Answer: B
A ready heap on the priority gives the best item now. A queue or heap on the time says when an item becomes ready or a worker becomes free.
Q2/4 One packer takes the shortest waiting order. Orders 0 to 3 arrive at times 1, 2, 3 and 4, with packing times 4, 3, 1 and 2. Which order is packed second?
Answer: B
Order 0 starts at time 1 and ends at time 5. Orders 1, 2 and 3 wait then, with times 3, 1 and 2. The shortest, order 2, goes next.
Q3/4 A kind of job runs at time 1 and must rest for 2 units. The next job of that kind starts at the earliest at which time?
Answer: C
The kind rests for the units 2 and 3, so it is ready again at time 1 + 2 + 1 = 4. The queue holds it with the ready time 4.
Q4/4 The ready heap is empty and the first resting item is ready at time 40. The clock is at 12. What is the cheapest correct step?
Answer: B
Nothing can run before time 40, so the clock can move there at once. The idle units cost no steps.
Checkpoint · A pool of workers
Q1/3 A pool needs two heaps. How are they ordered?
Answer: C
A job goes to the lightest free server, so the free heap is by weight and then number. The first server to finish is the next to become free, so the busy heap is by finish time.
Q2/3 A server finishes at time 5, and a job arrives at time 5. Is the server free for that job?
Answer: B
The rule in the problem and in the lab is that a finish time at or before the clock means the server is free. Treating it as busy changes the schedule.
Q3/3 Every server is busy when a job arrives. What does the desk do?
Answer: C
The job waits for the first server to finish. The clock jumps to that time, and the usual rule picks the lightest free server.
Checkpoint · Mistakes and limits
Q1/3 You build a playlist from the codes a, a, b. After taking a, what keeps the next code from being a again?
Answer: B
The heap would give a again, since it still has a track left. Holding it out makes the heap give b. Then a goes back into the heap.
Q2/3 100,000 orders of 10^7 time units each are packed one after another. Why should the clock be a 64-bit number?
Answer: B
Adding the durations gives up to 100,000 times 10^7, which is 10^12. A 32-bit int overflows near 2.147 billion.
Q3/3 All the jobs are known at the start and run in one fixed order of priority, with no rests. What is the simplest correct method?
Answer: C
A heap helps when the choice changes as items arrive, rest or finish. With a fixed order and nothing arriving, a single sort is enough.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.