Kodewick
Start learning →
Queues: deque and circular queues16 / 52

Queues: deque and circular queues

Lesson 16 of 52 · Part 3 · Stacks and queues · about 15 minutes

A queue is first in, first out: items join at one end and leave at the other; list.pop(0) shifts everything behind, so use collections.deque, O(1) at both ends, or a circular queue on a fixed-size list.

Print jobs, a website's message queue, the nodes waiting their turn in breadth-first search: all are handled first come, first served (FIFO, first in first out). A structure that stores things that way is a queue. The queue newcomers to Python write most is q.append(x) to join and q.pop(0) to leave: the result is right, but every pop(0) shifts every item behind it one cell forward, and emptying a queue of 100,000 items takes almost 5 billion moves. This lesson shows why, switches to collections.deque, and finally builds a circular queue by hand on a fixed-size list.

First in, first out

A queue has two ends: things join at the back (enqueue) and leave from the front (dequeue). Compared with a stack, only the leaving end is different:

In atOut atFirst out is
Stackthe topthe topthe last one in
Queuethe backthe frontthe first one in

With a list, the end is the back, and append to enqueue is fine; dequeuing takes the item at the front, which makes it pop(0).

Choose one

An empty queue: enqueue 1, 2, 3, dequeue once, enqueue 4, dequeue again. What do the two dequeues give, in order?

The wrong way: list.pop(0)

A list is a row of cells next to each other, and index 0 must hold the first item. Once index 0 is taken, every item behind it moves one cell left to fill the gap:

q102030405001234

q.pop(0) takes 10 from the front, and then 20, 30, 40 and 50 each move one cell left so the list starts at index 0 again

Count the moves for emptying a queue of 1000 items: each pop(0) moves the len(q) - 1 items behind it.

main.py
1n = 10002q = list(range(n))3moves = 04order = []5while q:6    moves += len(q) - 1       # every item after index 0 moves one cell left7    order.append(q.pop(0))8print("right order:", order == list(range(n)))9print("list.pop(0) moved items", moves, "times")10print("100,000 items would take", 100000 * 99999 // 2, "moves")
Output
right order: True
list.pop(0) moved items 499500 times
100,000 items would take 4999950000 moves

The order is exactly right, and the cost is 999 + 998 + … + 0 = n(n − 1) / 2, O(n²). At 1000 items you can't feel it; at 100,000 it is 4,999,950,000 moves.

Choose one

A list has n items and you dequeue them all one by one with pop(0). How many times do items move in total?

The right way: collections.deque

collections.deque (say "deck", a double-ended queue) goes in and out at both ends directly: inside, it is a chain of small blocks, and moving the front along only changes an index, with no item moved.

list.pop(0)x = q.pop(0)O(n)the n − 1 items behind all shift left
deque.popleft()x = q.popleft()O(1)no item moves
The same "take the front": a list shifts everything behind it, a deque only moves its front along by one
main.py
1from collections import deque2 3q = deque()4q.append("A")                 # enqueue: in on the right5q.append("B")6q.append("C")7print(q.popleft(), q.popleft())   # dequeue: out on the left8q.append("D")9print(list(q), len(q), q[0])10 11q.appendleft("Z")             # in on the left works too12print(q.pop(), list(q))       # and out on the right
Output
A B
['C', 'D'] 2 C
D ['Z', 'C']
Operationlistdeque
right end append / popO(1)O(1)
left endinsert(0, x) / pop(0): O(n)appendleft(x) / popleft(): O(1)
by index q[i]O(1)O(n) (fast near the ends)
slice q[1:3]yesno

deque(maxlen=k) is a queue that drops items once full: put a new one in at one end, and the oldest at the other end is pushed out.

Guess the outputA wrong guess is fine

A deque with maxlen=3: first append(4), then appendleft(0). What does it print?

1from collections import deque2 3q = deque([1, 2, 3], maxlen=3)4q.append(4)5q.appendleft(0)6print(list(q))
Choose one

Which of these collections.deque operations is O(n)?

A circular queue by hand

Interviews and exams often ask for "a queue on a fixed-size array" (LeetCode 622). The trick is to move no items and let the front's index move along instead; past the last cell it wraps round to 0, turning the list into a ring. Wrapping round is modulo: (i + 1) % cap.

You only need two numbers: head (the front's index) and size (how many there are). The next item at the back goes at (head + size) % cap; empty is size == 0, full is size == cap.

data (cap = 4)0123↑head

A circular queue of capacity 4: a dequeue only moves head along; the back wraps round to 0 after the last cell, and the cells freed at the front are used again
main.py
1class CircularQueue:2    def __init__(self, cap):3        self.data = [None] * cap4        self.cap = cap5        self.head = 0                # the front's index6        self.size = 0                # how many there are7 8    def enqueue(self, x):9        if self.size == self.cap:10            return False             # full11        self.data[(self.head + self.size) % self.cap] = x12        self.size += 113        return True14 15    def dequeue(self):16        if self.size == 0:17            raise IndexError("dequeue from empty queue")18        x = self.data[self.head]19        self.data[self.head] = None20        self.head = (self.head + 1) % self.cap21        self.size -= 122        return x23 24    def __len__(self):25        return self.size26 27q = CircularQueue(4)28for x in [1, 2, 3]:29    q.enqueue(x)30print(q.dequeue(), q.dequeue())31print([q.enqueue(x) for x in [4, 5, 6, 7]])32print(q.data, q.head, len(q))33while len(q):34    print(q.dequeue(), end=" ")35print()
Output
1 2
[True, True, True, False]
[5, 6, 3, 4] 2 4
3 4 5 6 

self.data[self.head] = None is not required, but it lets the object taken out be freed sooner, and printing shows at a glance which cells are empty.

The circular queue in exams often keeps no size, but front and rear (where the next item goes). Then empty and full are both front == rear and can't be told apart, so one cell is left empty on purpose:

head and size (this lesson)front and rear (common in exams)
the back goes at(head + size) % caprear, then rear = (rear + 1) % cap
emptysize == 0front == rear
fullsize == cap(rear + 1) % cap == front, holding at most cap − 1
lengthsize(rear - front + cap) % cap
Choose one

An exam-style circular queue: cap = 6, one slot left empty on purpose, front = 4, rear = 1. How many items are in it?

Choose one

This lesson’s version: cap = 5, head = 3, size = 4. Which slot does the next item go into?

In interviews: "Why not a list as the queue in BFS?" pop(0) is O(n); use deque.popleft(). For "design a circular queue", explain the modulo that wraps round and how full is told from empty (keep a size, or leave one cell empty).

Exercise 1

Write a circular queue

Fill in enqueue and dequeue: when full, enqueue returns False; when empty, dequeue returns None. The back goes at (head + size) % cap, and after a dequeue head moves along one, wrapping round with modulo.

It should print
True True True False
1 2
True True False
3 5 6 None
exercise1.py
1class CircularQueue:2    def __init__(self, cap):3        self.data = [None] * cap4        self.cap = cap5        self.head = 06        self.size = 07 8    def enqueue(self, x):9        return False      # full: False; otherwise put it in, add one to size, return True10 11    def dequeue(self):12        return None       # empty: None; otherwise take the front, move head, take one off size13 14q = CircularQueue(3)15print(q.enqueue(1), q.enqueue(2), q.enqueue(3), q.enqueue(4))16print(q.dequeue(), q.dequeue())17print(q.enqueue(5), q.enqueue(6), q.enqueue(7))18print(q.dequeue(), q.dequeue(), q.dequeue(), q.dequeue())
Output
Press Run or Ctrl+Enter

How you write it at work

Queues at work are nearly always collections.deque: append to enqueue, popleft to dequeue, if q: for not empty. You don't write circular queues yourself: deque(maxlen=n) is a ready-made ring buffer, for example to keep only the last few lines of a log:

main.py
1from collections import deque2 3last = deque(maxlen=3)        # keep only the latest 34for line in ["start", "connect to database", "read config", "handle request 1", "handle request 2"]:5    last.append(line)6print(list(last))7print(len(last), last.maxlen)
Output
['read config', 'handle request 1', 'handle request 2']
3 3
  • To pass work between threads, use the standard library's queue.Queue: it does its own locking, and get() waits while it is empty.
  • "Highest priority first" is not a plain queue: use heapq (the heap in Chapter 4).
  • Indexing into the middle of a deque is O(n); if you need lots of random access, it is the wrong tool.
Choose one

Several threads pass tasks to each other: one puts, another waits to take. What do you use from the standard library?

Exercise 2

Requests in the last 3000 ms

ping(t) receives a request at time t (in milliseconds, always increasing) and returns how many requests fall in [t - 3000, t]. Right now it only ever adds and never removes the old ones. With a deque: after adding t, popleft everything at the front that is less than t - 3000.

It should print
[1, 2, 3, 3, 1]
exercise2.py
1from collections import deque2 3class RecentCounter:4    def __init__(self):5        self.q = deque()6 7    def ping(self, t):8        self.q.append(t)9        # remove the ones that are too old from the front10        return len(self.q)11 12c = RecentCounter()13print([c.ping(t) for t in [1, 100, 3001, 3002, 7000]])
Output
Press Run or Ctrl+Enter

Summary

Take-away

Queues: in at the back, out at the front, first in first out

  • Never dequeue with list.pop(0): it shifts every item behind, O(n)
  • collections.deque: append to enqueue, popleft to dequeue, both O(1)
  • deque(maxlen=n) pushes the oldest out at the other end once full
  • A circular queue: head and size; the back at (head + size) % cap, empty size == 0, full size == cap
1from collections import deque2q = deque()3q.append(x)        # enqueue4x = q.popleft()    # dequeue5if q: ...          # not empty