Queue
how it works
The idea in a few sentences and three pictures, then one run step by step.
Think of people waiting at a counter. A number joins the line at the back, and only the one at the front can leave. So the first one in is the first one out, FIFO for short. Its formal name is a queue. A leave from an empty line gives nothing back and is not counted. The watch page draws everyone stepping forward after a leave, as people do. A program may do the same, moving every number, and section 4 counts those moves. Or it keeps the numbers where they joined, in a row of slots, with a mark on the front. Then no number moves, and each join or leave counts 1. A mark alone soon runs out of row, and a ring fixes that, as section 3's ring pictures show. The watch page shows each join in two steps, arriving and then joining, and each leave in one. This page counts each join and each leave once. The storyboard lets 4, 8 and 2 join, one leave, 6 join, then two leave.
Queue, oldest out. Numbers join at the right end, the back, and leave from the left end, the front.
Out, in turn: 4, 8, 2.
- just put in
- just taken out
Moving up. The front stays at slot 0, and a leave moves every number behind it one slot forward.
A mark on the front. A leave moves the mark one slot on, and no number moves.
- a number waiting
- just joined
- moved one slot forward
- just left
- an empty slot
- the front, next to leave
Queue, oldest out. Numbers join at the right end, the back, and leave from the left end, the front.
Out, in turn: 7, 1, 6, 3.
Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.
Out, in turn: 6, 3, 1, 7.
- just put in
- just taken out
step 2 of 13
4 arrives to join the line.
what it remembers to know where it is
- doing operation
- 1
- at the front
- not yet
- in the line
- 0
Where it says not yet, nothing is held there at that moment.
step 3 of 13
4 joins at the back. The line now holds one number.
what it remembers to know where it is
- doing operation
- 1
- at the front
- 4
- in the line
- 1
step 7 of 13
2 joins at the back. The line now holds 3 numbers.
what it remembers to know where it is
- doing operation
- 3
- at the front
- 4
- in the line
- 3
step 8 of 13
The number at the front, 4, leaves. 8 is now at the front.
what it remembers to know where it is
- doing operation
- 4
- at the front
- 8
- in the line
- 2
step 10 of 13
6 joins at the back. The line now holds 3 numbers.
what it remembers to know where it is
- doing operation
- 5
- at the front
- 8
- in the line
- 3
step 11 of 13
The number at the front, 8, leaves. 2 is now at the front.
what it remembers to know where it is
- doing operation
- 6
- at the front
- 2
- in the line
- 2
step 12 of 13
The number at the front, 2, leaves. 6 is now at the front.
what it remembers to know where it is
- doing operation
- 7
- at the front
- 6
- in the line
- 1
step 13 of 13
Done. The line holds one number.
what it remembers to know where it is
- doing operation
- not yet
- at the front
- 6
- in the line
- 1
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with an empty linePython line 11
- a number joins at the backPython lines 13 and 14
- the number at the front leavesPython lines 15 and 16
- an empty line has no one to leavePython lines 15 and 17
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from collections import deque
def queue(operations):
"""Run a list of operations on a line kept in a deque.
A number joins at the back, and None lets the front one leave.
Returns the line that is left, front first. It never compares
two numbers.
"""
line = deque() # an empty line
for op in operations:
if op is not None: # a number joins
line.append(op) # at the back, the right end
elif line: # the front one leaves, if there is one
line.popleft() # from the left end; no number moves
# an empty line has no one to leave, so None does nothing
return list(line)
how it scales
How the joins and leaves grow, from ten numbers to a million, each joining and then leaving.
Across and up, each mark is ten times the one before: a log-log plot. Every order of the numbers costs the same, joins and leaves. So the three orders, smallest first, shuffled and biggest first, draw one line. It climbs as far up as it goes across: 20 at 10 numbers, 2,000,000 at a million. Ten times the numbers, ten times the count.
joins and leaves, ten times more at each mark up
, n, ten times more at each mark to the right
- joined biggest first, down to 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- shuffled, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- joined smallest first, 1 to solid where measured by running it; dashed where its formula carries it on to ten million
| joins and leaves | time | |
|---|---|---|
| 1,000 | 2,000 | about 2 microseconds |
| 100,000 | 200,000 | about 200 microseconds |
| 10,000,000 | 20,000,000 | about 20 milliseconds |
The joins and leaves are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count a queue's joins and leaves yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it lets n numbers join
an empty line and then all leave, and prints the count for 1 to n in
order, n down to 1, and the average over 20 shuffles of 1 to n. Each join
counts 1, and so does each leave that gives a number back. The counts are
the same on any computer; only the time differs.
"""
import random
from collections import deque
def queue(operations):
"""Run a list of operations on a line kept in a deque.
A number joins at the back, and None lets the front one leave.
Returns the line that is left, front first. It never compares
two numbers.
"""
line = deque() # an empty line
for op in operations:
if op is not None: # a number joins
line.append(op) # at the back, the right end
elif line: # the front one leaves, if there is one
line.popleft() # from the left end; no number moves
# an empty line has no one to leave, so None does nothing
return list(line)
def cheapest(n):
"""1 to n join in order, then n leaves."""
return list(range(1, n + 1)) + [None] * n
def count(operations):
"""How many joins, and leaves that give a number back, the line makes."""
joins = sum(1 for op in operations if op is not None)
left = queue(operations)
# every number that joined is still in the line, or left once
return joins + (joins - len(left))
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>8} {'in order':>10} {'n down to 1':>12} {'shuffled':>10}")
for n in [10, 100, 1000, 10000, 100000]:
row = list(range(1, n + 1))
shuffles = []
for _ in range(20):
random.shuffle(row)
shuffles.append(count(row + [None] * n))
down = list(range(n, 0, -1)) + [None] * n
print(f"{n:>8} {count(cheapest(n)):>10} {count(down):>12} {sum(shuffles) / 20:>10.1f}")
best, worst and average
Every order costs the same: joins and leaves. No join or leave looks at a number's size or compares two numbers, so the order cannot change the count.
A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestjoined smallest first, 1 to | averageshuffled, every order as likely | worstjoined biggest first, down to 1 | |
|---|---|---|---|
| joins and leaves | , every order alike | , no more than the rest | |
| how the joins and leaves grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: none beside the row; a ring sized in advance needs room only for the most it holds at once, and one that doubles keeps spare room
Extra memory is the room it needs on top of the input itself, while it runs.
| order joined | joins | leaves | joins and leaves |
|---|---|---|---|
| 1, 2, 3, 4, 5 | 5 | 5 | 10 |
| 5, 4, 3, 2, 1 | 5 | 5 | 10 |
| 3, 5, 1, 4, 2 | 5 | 5 | 10 |
| 2, 1, 5, 3, 4 | 5 | 5 | 10 |
A mark on the front. A leave moves the mark one slot on, and no number moves.
A ring. Past the last slot, the mark and the next join carry on from slot 0.
- a number waiting
- just joined
- just left
- an empty slot
- the front, next to leave
A full ring, grown. Its numbers are copied, front first, into a ring twice as long, and then the join is written.
- a number waiting
- copied into the new ring, bracketed under it
- just joined
- an empty slot
- the front, next to leave
where the formula comes from
Each count above, worked out one small move at a time. Every line names the line or fact it uses, and each 'where does this come from?' box opens a fact from another page.
the move: count the joins
the line:A ring. Past the last slot, the mark and the next join carry on from slot 0.
- a number waiting
- just joined
- just left
- an empty slot
- the front, next to leave
Biggest first, here 7, 5, 3 and 1, in a ring of 4 slots, room for all 4. Each join writes one slot, and each leave moves the mark. 4 joins and 4 leaves, 8 in all, with no copies and no moves. why it is allowed: Joins and leaves count 1 each, as the concept page on what a structure promises counts them. Moves and copies are counted apart: moves in the moving-up question below, copies on the stack's page. A ring with room for every number never copies. joins count .
the move: count the leaves
the line:why it is allowed: Only as many leave as joined, so every leave gives a number back. leaves count .
guess it, thenthe move: add them
the line:why it is allowed: is the joins and leaves of numbers, biggest first. By lines 1 and 2. For 4, 4 + 4.
guess it, thenthe move: two lots of n
the line:why it is allowed: By line 3. For 4, 8, as the picture counts.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4: is , so it is both at most and at least . reads at most, and at least. For 4, 8 is at most 8 and at least 8.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, with the fixed multiple 2.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the order is never read
the line:why it is allowed: Lines 1 and 2 of the first question count every join and every leave as 1, whatever the numbers.
the move: add them
the line:why it is allowed: is the joins and leaves of 1 to in order, all joining, then all leaving. By line 1. For 4, 4 + 4.
guess it, thenthe move: two lots of n
the line:why it is allowed: By line 2. It is line 4 of the first question, so that question's lines 5 to 9 give here too.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: every order costs the same
the line:why it is allowed: By line 1 of the second question, no join or leave looks at a number's size or compares two numbers. The 6 orders of 1, 2 and 3 each count 6.
the move: average them
the line:why it is allowed: is the joins and leaves over every order of numbers, each as likely. By line 1, every order costs the same, by line 4 of the first question, and equal costs average to that cost. For 3, the 6 orders count 36, and 36 shared by 6 is 6. So the first question's lines 5 to 9 give here too.
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: a leave moves the rest up
the line:Moving up. The front stays at slot 0, and a leave moves every number behind it one slot forward.
- a number waiting
- just joined
- moved one slot forward
- just left
- an empty slot
- the front, next to leave
Four join, then four leave, the front kept at slot 0. The leaves move 3, 2, 1 and 0 numbers, 6 moves in all. why it is allowed: The front stays at slot 0. When its number leaves, each of the numbers behind it moves one slot forward. A join writes after the last number and moves none.
the move: add the moves
the line:why it is allowed: is the moves of joins, then leaves. By line 1 the joins move none, and the leaves find numbers, then one fewer each time. For 4, 3 + 2 + 1 + 0.
guess it, thenthe move: turn it round
the line:why it is allowed: By line 2, added in the other order, which gives the same. For 4, 0 + 1 + 2 + 3.
guess it, thenthe move: leave out the 0
the line:why it is allowed: By line 3. Adding 0 changes nothing. For 4, 1 + 2 + 3.
guess it, thenthe move: use the page on adding up
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line:Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15. why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The box under this line adds 1 up to a last number with two staircases: the sum is that last number times one more, halved. By line 4, here the last number is , and one more is . For 4, 1 + 2 + 3 is 3 times 4, halved, which is 6.
guess it, thenthe move: tidy
the line:why it is allowed: By line 5, as is . For 4, 3 times 4, halved, is 6, as the picture counts.
guess it, thenthe move: multiply out
the line:why it is allowed: By line 6, lots of are less . For 4, 16 less 4, halved, is 6.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 7 takes away before halving. Leaving it in gives more. For 4, 6 is at most 8.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, with the fixed multiple one half.
guess it, thenthe move: a fact about n
the line:why it is allowed: is times half of , and half of is at least 1 from 2 on. For 4, 4 is at most 8.
guess it, thenthe move: put line 10 into the top
the line:why it is allowed: By line 10, is at most half of . So line 7's top, less , is at least less half of , which is half of . For 4, the top 16 less 4 is 12, at least 16 less 8, which is 8.
guess it, thenthe move: halve it
the line:why it is allowed: By line 11, half of , halved, is a quarter of . For 4, halving 12 and 8 gives 6, at least 4.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 12, from 2 numbers on, with the fixed multiple one quarter.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 9 and 13 bound by the same growth, .
guess it, thenthe move: add the joins and leaves
the line:why it is allowed: Each join and each leave still counts 1, in all, as with a mark. Add to both sides of line 7. For 4, 6 + 8 is 14.
guess it, thenthe move: one denominator
the line:why it is allowed: By line 15, is halved, so both parts sit over 2. For 4, 16 less 4, plus 16, is 28, and 28 halved is 14.
guess it, thenthe move: collect the n terms
the line:why it is allowed: By line 16, less is . For 4, 16 + 12 is 28, and 28 halved is 14.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
Count every join and leave as 9, 7, 5 and 1 join, biggest first, then all four leave. Each dash in the input is a leave.
| step | the row | what happens | joined | left | joins and leaves |
|---|---|---|---|---|---|
| 1 | Start with an empty line, and 8 operations to do. | 0 | 0 | 0 | |
| 2 | 9 arrives to join the line. | 0 | 0 | 0 | |
| 3 | 9 | 9 joins at the back. The line now holds one number.9 | 1 | 0 | 1 |
| 4 | 9 | 7 arrives to join the line.9 | 1 | 0 | 1 |
| 5 | 9, 7 | 7 joins at the back. The line now holds 2 numbers.9, 7 | 2 | 0 | 2 |
| 6 | 9, 7 | 5 arrives to join the line.9, 7 | 2 | 0 | 2 |
| 7 | 9, 7, 5 | 5 joins at the back. The line now holds 3 numbers.9, 7, 5 | 3 | 0 | 3 |
| 8 | 9, 7, 5 | 1 arrives to join the line.9, 7, 5 | 3 | 0 | 3 |
| 9 | 9, 7, 5, 1 | 1 joins at the back. The line now holds 4 numbers.9, 7, 5, 1 | 4 | 0 | 4 |
| 10 | 7, 5, 1 | The number at the front, 9, leaves. 7 is now at the front.7, 5, 1 | 4 | 1 | 5 |
| 11 | 5, 1 | The number at the front, 7, leaves. 5 is now at the front.5, 1 | 4 | 2 | 6 |
| 12 | 1 | The number at the front, 5, leaves. 1 is now at the front.1 | 4 | 3 | 7 |
| 13 | The number at the front, 1, leaves. The line is empty again. | 4 | 4 | 8 | |
| 14 | Done. The line holds nothing. | 4 | 4 | 8 |
In all, 8 joins and leaves. The formula from section 4, , gives at : the same.
where you meet it
Lines wait wherever work arrives faster than it is done.
Python's deque
Python's deque, from its collections module, is a line with two open ends. append joins a number at the right end, an enqueue, and popleft lets the left one leave and gives it back, a dequeue. So a deque, said deck, is the line, and a dequeue is a leave. A join or a leave never moves another number. CPython, the usual Python, holds a deque in blocks of 64 places. A plain list does worse here: its pop(0) moves every other number one place forward, as Python's tutorial warns. On an empty deque, popleft stops with an error, IndexError.
source: Python's documentation, collections.deque (opens in a new tab), and its tutorial, Using Lists as Queues (opens in a new tab); CPython's Modules/_collectionsmodule.c, BLOCKLEN
connections waiting to be answered
A server is a program that answers other computers, and each caller first opens a connection to it. New connections wait in a line until the server takes them, and Linux usually holds that line to about 4,096. On Linux, a caller that finds the line full is dropped without a word, and it gets in on a later try once there is room. Some other systems refuse it at once instead. In Sebastian Bourges' books, 'A queue is where a system's performance actually lives' (volume two, chapter 21).
source: the Linux manual page listen(2) (opens in a new tab); Sebastian Bourges, Algorithmic Thinking Without the Jargon, volume two, chapter 21, 'Stacks and queues'
a printer's jobs
A printer takes the job that has waited longest, so its jobs wait in a line: oldest out, as Sebastian Bourges' books call a queue. The books point out that the other answer, newest first, would serve whoever asked last, a printer no one would want.
source: Sebastian Bourges, Algorithmic Thinking Without the Jargon, volume two, chapter 21, 'Stacks and queues'
| asked | gives | line after |
|---|---|---|
| line.append(4) | None | deque([4]) |
| line.append(8) | None | deque([4, 8]) |
| line.popleft() | 4 | deque([8]) |
| line.popleft() | 8 | deque([]) |
| line.popleft() | IndexError | deque([]) |
| queue([4, 8, None, None, None]) | [] | in this page's Python, None in the list stands for a leave; the last finds the line empty |
what is used instead
When some jobs must go first, arrival order is the wrong rule. At a help desk, a call saying the site is down goes before one about a forgotten password, even if it came later. Sebastian Bourges' books send that case to a priority queue (volume two, exercise 21.6 and its answer). The binary heap, a tree kept in a row with the smallest number on top, builds one on its learn page. When the newest must come first, as with undo, use a stack.
how it compares
Three ways to keep a line, side by side. Each lets numbers join, then all leave.
| way | a join | a leave | all in then all out | room | reach for it when |
|---|---|---|---|---|---|
| moving up | writes after the last number | moves every number behind the front | joins and leaves, and moves | only the most it holds | never; a mark moves nothing |
| a mark on the front | writes after the last number | moves the mark on | joins and leaves, no moves | every slot ever written | the line is filled once and then emptied |
| a ring | writes the next free slot | moves the mark on, past the last slot to slot 0 | joins and leaves, no moves; a full ring first grows | the most it holds, if sized in advance | almost always |
- a mark or a ring,
- moving up,