Simulate round-robin turns, eliminations and rounds with a queue, and process work level by level, the step before BFS (A1).
A shared build worker runs tasks from a line. It takes the task at the front and works on it for a short turn. If the task is not finished, it goes to the back of the line, and the next task gets a turn. Your job is to say when each task will finish.
You could write down every unit of time and move tasks by hand. That works for ten tasks. A build can have 100,000 tasks of thousands of units each, and replaying every unit of time costs half a billion steps. You need a way to act the line out in one step for each turn.
You already know the queue from queues and deques: add at the back, take from the front. This lesson uses it to act out processes. The queue is the line, and each step of the process is one move at its two ends.
Children take turns on one swing. Each child gets two minutes. When the time is up, a child who wants more goes to the back of the line, and the next child gets on. A child who is done goes home.
The line is the queue, two minutes is the turn, and the child who goes to the back is the task with work left. The playground clock is the clock of the simulation.
Children share a swing: a child who wants more goes to the back of the line, and the playground clock keeps the time.
Every simulation in this lesson has the same loop. Take the item at the front of the queue and decide what happens to it. Then either add it to the back, possibly changed, or let it go. The queue always holds what is still waiting, in the order it will be handled.
A few details change from problem to problem: what is stored in the queue, what counts as a turn, and when an item leaves for good. The two ends never change.
Step by step: A line of tasks on a ring and on a linked list. The animated player loads in your browser.
Predict what happens
Q The line holds tasks A, B and C, with A at the front. A runs one turn and still has work left. What is the line afterwards?
Answer: C
The front is taken, A runs one turn, and it still has work left. So it joins the back. B and C each move one place forward.
A round-robin turn is two queue moves: take the front, and add it to the back if it has work left. Take tasks of work 5, 2 and 7, and a turn of 3. The first task runs 3 units and has 2 left, so it goes to the back. The second needs only 2, so it runs 2 units and is done.
The clock moves by the units used: 3, then 2, not 3 and 3. That is how the finish times come out right. For these three tasks, the finish times are 10, 5 and 14. The worker takes six turns, and the total work is 14 units.
One turn: the front task runs for the smaller of the turn and its work, the clock moves by that, then it goes back or is done.
Step by step: One turn: the front goes to the back. The animated player loads in your browser.
Predict what happens
Q Two tasks need 3 and 6 units, and a turn is 5 units. At what clock time does the second task finish?
Answer: C
The clock moves by the units used. The first task runs 3 units, so the clock is 3. The second runs 5, so the clock is 8, and it has 1 left. Its last turn runs 1 unit, and the clock is 9.
Exercise · Predict the output: When does each task finish?. Three tasks need 4, 1 and 6 units of work, and a turn is 3 units. The worker takes the front task, runs it for up to one turn, and sends it to the back if work is left. What does this print: the finish time of each task, in task order?
from collections import deque
work = [4, 1, 6]
turn = 3
left = work[:]
finish = [0] * len(work)
line = deque(range(len(work)))
clock = 0
while line:
task = line.popleft()
used = min(turn, left[task])
clock += used
left[task] -= used
if left[task] > 0:
line.append(task)
else:
finish[task] = clock
print(*finish)A circle is a queue where the front goes to the back. To count off 3 in a circle of 5, move 2 entrants from the front to the back. The next entrant is the third counted, so remove them. The next round starts from the one after.
With entrants 1 to 5 and a count of 3, the order out is 3, 1, 5 and 2, and entrant 4 is left. Each round moves (k - 1) modulo the size of the circle, because a full lap does not change anything. For a circle of 2 and a count of 3, that is 0 moves.
Exercise · Break it: Find the circle where the wrong entrant is out. This function counts off k in a circle of n entrants numbered 1 to n, removes the one counted, and returns the last entrant standing. Find an input where it gives the wrong answer.
from collections import deque
def last_standing(n, k):
circle = deque(range(1, n + 1))
while len(circle) > 1:
for _ in range(k):
circle.append(circle.popleft())
circle.popleft()
return circle[0]Counting off three: move two entrants from the front to the back, and the entrant now at the front is out.
Step by step: Count off 3 in a circle of 5. The animated player loads in your browser.
Predict what happens
Q A circle holds 1, 2, 3, 4, 5, with 1 at the front. You count off 3. Who is out, and who is at the front for the next round?
Answer: B
Move 1 and 2 from the front to the back. Entrant 3 is now at the front, so they are out. Entrant 4 is next, and the circle is 4, 5, 1, 2.
Some problems give you a procedure and ask for the input that makes it come out in order. Do not search for the values. Run the procedure on the positions with a queue, and note the order in which positions are reached.
A stack of five banners shows the top one, removes it, and moves the next banner to the bottom. The positions are reached in the order 0, 2, 4, 3, 1. The sorted ids 2, 4, 5, 7 and 9 go to those positions in that order, so the stack is 2, 9, 4, 7, 5, top first.
Two teams take turns in rounds. Each team has a queue of positions, in speaking order. The smaller front speaks first, and removes the other front. The speaker joins the back of their own queue, with n added to their position, so that they speak after everyone in this round.
For the room ABB, team A has position 0 and team B has positions 1 and 2. A speaks first and removes B at 1, and rejoins as position 3. Then B at 2 is smaller than 3, so B speaks first and removes A. Team B wins, though A spoke first.
Exercise · Find the bug: The speaker who keeps their place. Two teams, A and B, take turns in rounds, as described above. The smaller front position speaks first, removes the other front, and joins the back of its own queue. This function returns the winning team, but it gives the wrong team on some rooms. Which line is wrong?
from collections import deque
def winner(room):
n = len(room)
a, b = deque(), deque()
for i, ch in enumerate(room):
if ch == "A":
a.append(i)
else:
b.append(i)
while a and b:
x, y = a.popleft(), b.popleft()
if x < y:
a.append(x + n)
else:
b.append(y)
return "A" if a else "B"Some processes work in rounds. In round 1, handle everything that is waiting. Whatever that creates waits for round 2. To do this, read the size of the queue at the start of a round and handle exactly that many items.
An update spreads from server 0. Server 0 passes it to 1 and 2. Server 1 passes it to 3 and 4, server 2 passes it to 5, and server 3 passes it to 6. The rounds have the servers [0], [1, 2], [3, 4, 5] and [6], so the update takes four rounds.
from collections import deque
def rounds(start, passes_to):
queue = deque([start])
count = 0
while queue:
for _ in range(len(queue)): # exactly the servers waiting at the start of the round
server = queue.popleft()
for target in passes_to[server]:
queue.append(target) # these wait for the next round
count += 1
return countProcess in rounds: read the size of the queue, handle that many items, and let the new items wait for the next round.
Exercise · Put it in order: Count the rounds. An update starts at server 0, and passes_to[s] lists the servers that server s passes it to. Arrange the lines into a function that counts the rounds, where a round handles exactly the servers that were waiting when it began.
def count_rounds(passes_to):
queue = [0]
head = 0
count = 0
while head < len(queue):
for _ in range(len(queue) - head):
server = queue[head]
head += 1
queue.extend(passes_to[server])
count += 1
return count
for _ in range(len(queue)):This loop is breadth-first search without a visited set. In graph search, the items are nodes and the new items are the neighbours of a node. A visited set stops a node from joining twice. The BFS lesson in the algorithm part adds exactly that, and shows the rounds as distances from the start.
Predict what happens
Q A round starts with 3 servers in the queue. During the round, those 3 servers add 5 new servers. How many servers does the same round handle?
Answer: B
The loop runs for the size of the queue at the start of the round. The 5 new servers join the back and are handled in the next round.
Here is the queue next to two other ways to act out a line.
| Operation | Queue (deque or ring) | Plain list with pop(0) | Act out each unit of time |
|---|---|---|---|
| Add a task at the back (enqueue) | O(1) | O(1): append | O(1) |
| Remove the front (dequeue) | O(1) | O(n): every item shifts | O(1) for each unit of work |
| Peek at the front | O(1) | O(1) | O(1) |
| Search for a given task | O(n) | O(n) | O(n) |
| Send the front to the back (a turn of the deque) | O(1) | O(n) | O(turn) |
| A whole run with n tasks and t turns | O(n + t) | O(n × t) | O(total work) |
A queue wins when a long line is acted out. A replay of every unit is the same cost as the total work, which is far larger than the number of turns.
Now drive the queue yourself. Use the ring or the linked variant. A turn is a dequeue followed by an enqueue of the same value.
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 turn queue yourself. The lab gives you a TurnQueue class. You write seven methods: add_task, run_turn, front_left, waiting, done, clock and size.
Four things to take care over:
run_turn takes the front, runs it for min(turn, work left) units, and moves the clock by the units used, never by the whole turn.run_turn and does not move the clock. A task with 0 work finishes at once and uses no time.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 queue to act out a process where items are handled from the front and some go back. Examples are turns, retries, counting off, and procedures that move items from the top to the bottom. Rounds fit too, with the size of the queue read at the start.
Each step is O(1), so a run costs about one step for each turn.
If items are handled by priority, not arrival, use a heap. If you need to jump to an item by its position, use an array. If a formula gives the answer, such as the winner of a counting-off circle, a queue is only a way to check the formula on small inputs.
A task with work left goes to the back of the line. If it goes to the front, it runs again at once and starves the others. For work 8, 8 and a turn of 5, the first task would finish at 8. The right finish times are 13 and 16.
line.appendleft(task) # wrong: the task runs again at once
line.append(task) # right: it waits behind the othersMove the clock by the units used, not by the whole turn: a task that needs less than a turn must not cost a full turn.
A task that needs less than a turn uses only the units it needs. For work 3, 6 and a turn of 5, the first task uses 3 units, not 5. Moving the clock by the whole turn gives [5, 15] and the right finish times are [3, 9].
clock += turn # wrong: the task may need less
clock += min(turn, left) # rightThe count starts at the front. The front is the first entrant counted, so only k minus 1 entrants move before the k-th is at the front. For 3 entrants and a count of 2, moving 2 entrants removes the wrong one and the winner is 2, not 3.
circle.rotate(-k) # wrong: removes the (k+1)-th entrant
circle.rotate(-(k - 1)) # rightA round is everything that was waiting when it started. If you add 1 to the round count for each item you take, you count items and not rounds. For the update that spreads over [0], [1, 2], [3, 4, 5] and [6], that gives 7 and not 4.
count += 1 # wrong: inside the loop over items
count += 1 # right: once, after the loop over the roundExplain 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 · The loop and the turn
Q1/3 What is the loop of a queue simulation?
Answer: B
The two ends never change: items leave at the front and join at the back. What changes is what happens in between.
Q2/3 A round-robin worker runs tasks with work 4 and 9 in turns of 6. A task with work left goes to the back. In what order do the tasks finish?
Answer: B
The first task needs 4 units, which is less than a turn, so it finishes in its first turn. The second runs 6 units, goes to the back, and finishes later.
Q3/3 Which clock time does the last task reach, for work 3, 6 and a turn of 5?
Answer: C
The first task uses 3 units, the second runs 5 and has 1 left, and its second turn runs 1 unit. The clock is 3, 8 and 9.
Checkpoint · Counting off and procedures
Q1/3 In a circle of 6, you count off 4. How many entrants move from the front to the back before the removal?
Answer: B
The front is the first entrant counted. So k minus 1 entrants move before the k-th is at the front, and 4 minus 1 is 3.
Q2/3 A circle holds 4 entrants and you count off 6. How many moves does the first round need?
Answer: C
Whole laps change nothing. The count of 6 needs 5 moves, and 5 modulo 4 is 1.
Q3/3 A stack shows the top banner, removes it, and moves the next one to the bottom. How do you find which position is shown first, second and third?
Answer: B
The order of positions depends only on how many banners there are. A queue acts it out once, and the sorted values fill the positions.
Checkpoint · Teams and rounds
Q1/4 Two teams use two queues of positions. The fronts are 4 and 7. Who speaks first, and what happens to that speaker?
Answer: B
The smaller position speaks first. The speaker rejoins its own queue with n added, so it speaks after everyone in this round.
Q2/4 A round starts with 4 items in the queue. They add 6 new items during the round. How many does the same round handle?
Answer: B
The size is read at the start of the round. The 6 new items wait for the next round.
Q3/4 Counting every item as a round gives the wrong number of rounds. For an update that spreads over the levels [0], [1, 2], [3, 4, 5] and [6], what is the right count?
Answer: C
A round is a whole level. There are 4 levels, so there are 4 rounds. Counting items would give 7.
Q4/4 What does breadth-first search add to the round by round loop?
Answer: B
The loop handles the neighbours of each node in rounds. A visited set stops a node from joining twice, and the round number becomes the distance from the start.
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.