Skip to content

Queue

storing

Level 1 of 3

Also called First in, first out.

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.

join 44join 848join 2482leave824gives 4join 6826leave268gives 8leave62gives 2

Out, in turn: 4, 8, 2.

  • just put in
  • just taken out
The storyboard's seven operations, one a row, as the watch page draws them. After each leave, the rest step forward. 4, 8 and 2 come out, and 6 stays.

Moving up. The front stays at slot 0, and a leave moves every number behind it one slot forward.

slot0123movesjoin 440join 8480join 24820leave482gives 42join 68260leave826gives 82leave26gives 21Moves in all: 5.

A mark on the front. A leave moves the mark one slot on, and no number moves.

slot0123movesjoin 440join 8480join 24820leave 44820join 68260leave 88260leave 2260Moves in all: 0.
  • a number waiting
  • just joined
  • moved one slot forward
  • just left
  • an empty slot
  • the front, next to leave
The same seven operations in a row of 4 slots, kept two ways. Moving every number up costs 5 moves. A mark on the front costs none, as each number stays where it joined.

Queue, oldest out. Numbers join at the right end, the back, and leave from the left end, the front.

join 77join 171join 6716leave167gives 7join 3163leave631gives 1leave36gives 6leave3gives 3

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.

put 77put 171put 6716take716gives 6put 3713take713gives 3take71gives 1take7gives 7

Out, in turn: 6, 3, 1, 7.

  • just put in
  • just taken out
The same eight operations, fed to a queue and to a stack. They agree until the first leave. Then the queue gives back the oldest, 7, and the stack the newest, 6.
Joining and leaving: 8 moments of its 13 steps, the steps between them left for the watch page
  1. step 2 of 13

    4

    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.

    watch from here

  2. step 3 of 13

    4

    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

    watch from here

  3. step 7 of 13

    482

    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

    watch from here

  4. step 8 of 13

    82

    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

    watch from here

  5. step 10 of 13

    826

    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

    watch from here

  6. step 11 of 13

    26

    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

    watch from here

  7. step 12 of 13

    6

    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

    watch from here

  8. step 13 of 13

    6

    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.

    watch from here

the steps, in plain words
  1. start with an empty linePython line 11
  2. a number joins at the backPython lines 13 and 14
  3. the number at the front leavesPython lines 15 and 16
  4. 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, 2n2n 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

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, n, ten times more at each mark to the right

  • joined biggest first, nn 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 nnsolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion joins and leaves a second
nnjoins and leavestime
1,0002,000about 2 microseconds
100,000200,000about 200 microseconds
10,000,00020,000,000about 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: nn joins and nn 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestjoined smallest first, 1 to nnaverageshuffled, every order as likelyworstjoined biggest first, nn down to 1
joins and leaves2n2n2n2n, every order alike2n2n, no more than the rest
how the joins and leaves grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)Θ(n)\Theta(n)
ceiling, OOO(n)O(n)O(n)O(n)O(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)Ω(n)\Omega(n)

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 joinedjoinsleavesjoins and leaves
1, 2, 3, 4, 55510
5, 4, 3, 2, 15510
3, 5, 1, 4, 25510
2, 1, 5, 3, 45510
Four orders of 1 to 5, each joining, then all leaving. Each counts 10.

A mark on the front. A leave moves the mark one slot on, and no number moves.

slot0123movesjoin 990join 5950leave 9950join 7570leave 5570join 3730join 873no roomMoves in all: 0.

A ring. Past the last slot, the mark and the next join carry on from slot 0.

slot0123movesjoin 990join 5950leave 9950join 7570leave 5570join 3730join 88730Moves in all: 0.
  • a number waiting
  • just joined
  • just left
  • an empty slot
  • the front, next to leave
Seven operations in a row of 4 slots. With a mark alone, 8 finds no slot after slot 3, though slots 0 and 1 stand empty. In the ring, the front is at slot 2 with 2 numbers held, so 8 goes 2 slots on, to slot 4. That is past slot 3, so it carries on to slot 0. A mark alone needs a slot for every number that ever joined, 5 here. A ring sized in advance needs only the most held at once, 3 here. A ring that doubles keeps spare room.

A full ring, grown. Its numbers are copied, front first, into a ring twice as long, and then the join is written.

slot0123full ring8473slot01234567new ring738464 copied, then 6 joins
  • a number waiting
  • copied into the new ring, bracketed under it
  • just joined
  • an empty slot
  • the front, next to leave
The same ring, then 4 fills slot 1, and 6 finds every slot full, the front at slot 2. The 4 numbers are copied, front first, into a ring of 8 from slot 0. Then 6 joins at slot 4.

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.

Why do nn numbers that join, then all leave, count 2n2n joins and leaves, biggest first or in any order?
  1. the move: count the joins

    the line:
    each join writesone slot: it counts 1\begin{gathered} \text{each join writes} \\ \text{one slot: it counts 1} \end{gathered}

    A ring. Past the last slot, the mark and the next join carry on from slot 0.

    slot0123movesjoin 770join 5750join 37530join 175310leave 775310leave 55310leave 3310leave 110Moves in all: 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. nn joins count nn.

  2. the move: count the leaves

    the line:
    each leave gives backthe front and movesthe mark: it counts 1\begin{gathered} \text{each leave gives back} \\ \text{the front and moves} \\ \text{the mark: it counts 1} \end{gathered}

    why it is allowed: Only as many leave as joined, so every leave gives a number back. nn leaves count nn.

  3. the move: add them

    the line:
    J=n+nJ = n + n

    why it is allowed: JJ is the joins and leaves of nn numbers, biggest first. By lines 1 and 2. For 4, 4 + 4.

  4. the move: two lots of n

    the line:
    J=2nJ = 2n

    why it is allowed: By line 3. For 4, 8, as the picture counts.

  5. the move: a ceiling

    the line:
    J≤2nJ \le 2n

    why it is allowed: By line 4: JJ is 2n2n, so it is both at most and at least 2n2n. OO reads at most, and Ω\Omega at least. For 4, 8 is at most 8 and at least 8.

  6. the move: read it as a bound

    the line:
    J∈O(n)J \in O(n)

    why it is allowed: By line 5, with the fixed multiple 2.

  7. the move: a floor

    the line:
    J≥2nJ \ge 2n

    why it is allowed: By line 4 again.

  8. the move: read it as a bound

    the line:
    J∈Ω(n)J \in \Omega(n)

    why it is allowed: By line 7, with the fixed multiple 2.

  9. the move: ceiling and floor together

    the line:
    J∈Θ(n)J \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound JJ by the same growth, nn.

try it with a small nn: at n=4n = 4, line 3 gives J=8J = 8, which you can work out by hand

Why do numbers that join in order, smallest first, count the same 2n2n?
  1. the move: the order is never read

    the line:
    no join or leavecompares numbers, soin order costs the same\begin{gathered} \text{no join or leave} \\ \text{compares numbers, so} \\ \text{in order costs the same} \end{gathered}

    why it is allowed: Lines 1 and 2 of the first question count every join and every leave as 1, whatever the numbers.

  2. the move: add them

    the line:
    B=n+nB = n + n

    why it is allowed: BB is the joins and leaves of 1 to nn in order, all joining, then all leaving. By line 1. For 4, 4 + 4.

  3. the move: two lots of n

    the line:
    B=2nB = 2n

    why it is allowed: By line 2. It is line 4 of the first question, so that question's lines 5 to 9 give Θ(n)\Theta(n) here too.

try it with a small nn: at n=4n = 4, line 2 gives B=8B = 8, which you can work out by hand

Why do shuffled numbers count 2n2n joins and leaves on average?
  1. the move: every order costs the same

    the line:
    every order countsthe same joins and leaves\begin{gathered} \text{every order counts} \\ \text{the same joins and leaves} \end{gathered}

    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.

  2. the move: average them

    the line:
    A=2nA = 2n

    why it is allowed: AA is the joins and leaves over every order of nn numbers, each as likely. By line 1, every order costs the same, 2n2n 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 Θ(n)\Theta(n) here too.

try it on small rows: over every order of 4 numbers, the average is A=8A = 8

Keep the front at slot 0 instead, moving every number up on each leave. How many moves do nn joins, then nn leaves, make? And how many with the joins and leaves?
  1. the move: a leave moves the rest up

    the line:
    a leave from k numbersmoves the k−1behind the front\begin{gathered} \text{a leave from } k \text{ numbers} \\ \text{moves the } k - 1 \\ \text{behind the front} \end{gathered}

    Moving up. The front stays at slot 0, and a leave moves every number behind it one slot forward.

    slot0123movesjoin 220join 7270join 52750join 927590leave2759gives 23leave759gives 72leave59gives 51leave9gives 90Moves in all: 6.
    • 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 k−1k - 1 numbers behind it moves one slot forward. A join writes after the last number and moves none.

  2. the move: add the moves

    the line:
    M=(n−1)+⋯+1+0M = (n - 1) + \dots + 1 + 0

    why it is allowed: MM is the moves of nn joins, then nn leaves. By line 1 the joins move none, and the leaves find nn numbers, then one fewer each time. For 4, 3 + 2 + 1 + 0.

  3. the move: turn it round

    the line:
    M=0+1+⋯+(n−1)M = 0 + 1 + \dots + (n - 1)

    why it is allowed: By line 2, added in the other order, which gives the same. For 4, 0 + 1 + 2 + 3.

  4. the move: leave out the 0

    the line:
    M=1+2+⋯+(n−1)M = 1 + 2 + \dots + (n - 1)

    why it is allowed: By line 3. Adding 0 changes nothing. For 4, 1 + 2 + 3.

  5. the move: use the page on adding up

    the line:
    M=(n−1)((n−1)+1)2M = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      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 nn 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 n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    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 n−1n - 1, and one more is (n−1)+1(n - 1) + 1. For 4, 1 + 2 + 3 is 3 times 4, halved, which is 6.

  6. the move: tidy

    the line:
    M=(n−1)n2M = \frac{(n - 1)n}{2}

    why it is allowed: By line 5, as (n−1)+1(n - 1) + 1 is nn. For 4, 3 times 4, halved, is 6, as the picture counts.

  7. the move: multiply out

    the line:
    M=n2−n2M = \frac{n^2 - n}{2}

    why it is allowed: By line 6, nn lots of n−1n - 1 are n2n^2 less nn. For 4, 16 less 4, halved, is 6.

  8. the move: a ceiling

    the line:
    M≤n22M \le \frac{n^2}{2}

    why it is allowed: Line 7 takes nn away before halving. Leaving it in gives more. For 4, 6 is at most 8.

  9. the move: read it as a bound

    the line:
    M∈O(n2)M \in O(n^2)

    why it is allowed: By line 8, with the fixed multiple one half.

  10. the move: a fact about n

    the line:
    n≤n22 for n≥2n \le \frac{n^2}{2} \text{ for } n \ge 2

    why it is allowed: n22\frac{n^2}{2} is nn times half of nn, and half of nn is at least 1 from 2 on. For 4, 4 is at most 8.

  11. the move: put line 10 into the top

    the line:
    M≥n222 for n≥2M \ge \frac{\frac{n^2}{2}}{2} \text{ for } n \ge 2

    why it is allowed: By line 10, nn is at most half of n2n^2. So line 7's top, n2n^2 less nn, is at least n2n^2 less half of n2n^2, which is half of n2n^2. For 4, the top 16 less 4 is 12, at least 16 less 8, which is 8.

  12. the move: halve it

    the line:
    M≥n24 for n≥2M \ge \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: By line 11, half of n2n^2, halved, is a quarter of n2n^2. For 4, halving 12 and 8 gives 6, at least 4.

  13. the move: read it as a bound

    the line:
    M∈Ω(n2)M \in \Omega(n^2)

    why it is allowed: By line 12, from 2 numbers on, with the fixed multiple one quarter.

  14. the move: ceiling and floor together

    the line:
    M∈Θ(n2)M \in \Theta(n^2)

    why it is allowed: Lines 9 and 13 bound MM by the same growth, n2n^2.

  15. the move: add the joins and leaves

    the line:
    M+2n=n2−n2+2nM + 2n = \frac{n^2 - n}{2} + 2n

    why it is allowed: Each join and each leave still counts 1, 2n2n in all, as with a mark. Add 2n2n to both sides of line 7. For 4, 6 + 8 is 14.

  16. the move: one denominator

    the line:
    M+2n=n2−n+4n2M + 2n = \frac{n^2 - n + 4n}{2}

    why it is allowed: By line 15, 2n2n is 4n4n halved, so both parts sit over 2. For 4, 16 less 4, plus 16, is 28, and 28 halved is 14.

  17. the move: collect the n terms

    the line:
    M+2n=n2+3n2M + 2n = \frac{n^2 + 3n}{2}

    why it is allowed: By line 16, 4n4n less nn is 3n3n. For 4, 16 + 12 is 28, and 28 halved is 14.

try it with a small nn: at n=4n = 4, line 2 gives M=6M = 6, 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.

9, 7, 5, 1, -, -, -, -, every step written down
stepthe rowwhat happensjoinedleftjoins and leaves
1Start with an empty line, and 8 operations to do.000
29 arrives to join the line.000
399 joins at the back. The line now holds one number.9101
497 arrives to join the line.9101
59, 77 joins at the back. The line now holds 2 numbers.9, 7202
69, 75 arrives to join the line.9, 7202
79, 7, 55 joins at the back. The line now holds 3 numbers.9, 7, 5303
89, 7, 51 arrives to join the line.9, 7, 5303
99, 7, 5, 11 joins at the back. The line now holds 4 numbers.9, 7, 5, 1404
107, 5, 1The number at the front, 9, leaves. 7 is now at the front.7, 5, 1415
115, 1The number at the front, 7, leaves. 5 is now at the front.5, 1426
121The number at the front, 5, leaves. 1 is now at the front.1437
13The number at the front, 1, leaves. The line is empty again.448
14Done. The line holds nothing.448

In all, 8 joins and leaves. The formula from section 4, 2n2n, gives J=8J = 8 at n=4n = 4: 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'

askedgivesline after
line.append(4)Nonedeque([4])
line.append(8)Nonedeque([4, 8])
line.popleft()4deque([8])
line.popleft()8deque([])
line.popleft()IndexErrordeque([])
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
A deque called line, empty at first, asked in turn. append gives None, Python's word for nothing. The third popleft finds the line empty. The last row asks this page's Python.

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 nn numbers join, then all leave.

waya joina leaveall in then all outroomreach for it when
moving upwrites after the last numbermoves every number behind the front2n2n joins and leaves, and (n−1)n2\frac{(n - 1)n}{2} movesonly the most it holdsnever; a mark moves nothing
a mark on the frontwrites after the last numbermoves the mark on2n2n joins and leaves, no movesevery slot ever writtenthe line is filled once and then emptied
a ringwrites the next free slotmoves the mark on, past the last slot to slot 02n2n joins and leaves, no moves; a full ring first growsthe most it holds, if sized in advancealmost always
Each join and each leave counts 1. Moves and copies are counted apart: a move shifts a number one slot, and a copy fills a bigger ring. A ring with room for every number never copies.
10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
  • a mark or a ring, 2n2n
  • moving up, n2+3n2\frac{n^2 + 3n}{2}
All in, then all out, on a log-log plot, the moves added to the joins and leaves. A mark counts 200 at 100 numbers and 2,000 at 1,000, ten times as many. Moving up counts 5,150 and 501,500, about a hundred times as many for ten times the numbers.