TExcelTAD

Queues and Circular Buffers

A queue removes elements in the order they arrived: first in, first out (FIFO). Insertion is called ENQUEUE and adds at the tail; deletion is DEQUEUE and removes from the head. Queues hold the frontier of breadth-first search, the jobs waiting for a printer, the packets in a router, the events of a simulation.

The difficulty is the same as for any array-based structure that removes from the front: shifting all elements one place left after each DEQUEUE costs Θ(n)\Theta(n). The standard solution is to let the occupied part of the array wrap around, a circular buffer, which makes both operations O(1)O(1). The Queues lesson in the DSA course introduces the structure; this lesson builds the circular version and checks it.

The interface

A circular buffer

Keep an array q[0:m]q[0:m], an index head\textit{head} of the oldest element and a count size\textit{size}. The elements are at positions head,head+1,…\textit{head}, \textit{head} + 1, \ldots, taken modulo mm: after position m−1m - 1 comes position 0 again. The next free slot is (head+size) mod m(\textit{head} + \textit{size}) \bmod m.

text
ENQUEUE(q, x)                             DEQUEUE(q)
1  if q.size == m                         1  if q.size == 0
2      error "overflow"                   2      error "underflow"
3  q.a[(q.head + q.size) mod m] = x       3  x = q.a[q.head]
4  q.size = q.size + 1                    4  q.head = (q.head + 1) mod m
                                          5  q.size = q.size - 1
                                          6  return x

Invariant: the queue's elements, oldest first, are q.a[(head+i) mod m]q.a[(\textit{head} + i) \bmod m] for i=0,…,size−1i = 0, \ldots, \textit{size} - 1. ENQUEUE writes the position right after the last element and increases the count; DEQUEUE reads the first element and advances head\textit{head}. Both keep the invariant, and both are O(1)O(1). The program runs the operations of the animation on a buffer of 4 slots and then keeps going, so the occupied part wraps past the end.

python · try it yourself
class Queue:
    def __init__(self, m):
        self.a, self.head, self.size = [None] * m, 0, 0
    def enqueue(self, x):
        if self.size == len(self.a):
            raise OverflowError("queue overflow")
        self.a[(self.head + self.size) % len(self.a)] = x
        self.size += 1
    def dequeue(self):
        if self.size == 0:
            raise IndexError("queue underflow")
        x, self.a[self.head] = self.a[self.head], None      # clear the slot for the printout
        self.head = (self.head + 1) % len(self.a)
        self.size -= 1
        return x
    def peek(self):
        return self.a[self.head]
    def items(self):
        return [self.a[(self.head + i) % len(self.a)] for i in range(self.size)]

q = Queue(4)
ops = ["enqueue 4", "enqueue 7", "enqueue 2", "dequeue", "enqueue 9", "peek", "dequeue", "dequeue",
       "enqueue 5", "enqueue 6", "enqueue 8"]
for op in ops:
    name, *arg = op.split()
    r = getattr(q, name)(*map(int, arg))
    shown = "" if r is None else f"-> {r}"
    print(f"{op:10}{shown:5} queue {str(q.items()):13} slots {q.a}  head {q.head}")
enqueue 4       queue [4]           slots [4, None, None, None]  head 0
enqueue 7       queue [4, 7]        slots [4, 7, None, None]  head 0
enqueue 2       queue [4, 7, 2]     slots [4, 7, 2, None]  head 0
dequeue   -> 4  queue [7, 2]        slots [None, 7, 2, None]  head 1
enqueue 9       queue [7, 2, 9]     slots [None, 7, 2, 9]  head 1
peek      -> 7  queue [7, 2, 9]     slots [None, 7, 2, 9]  head 1
dequeue   -> 7  queue [2, 9]        slots [None, None, 2, 9]  head 2
dequeue   -> 2  queue [9]           slots [None, None, None, 9]  head 3
enqueue 5       queue [9, 5]        slots [5, None, None, 9]  head 3
enqueue 6       queue [9, 5, 6]     slots [5, 6, None, 9]  head 3
enqueue 8       queue [9, 5, 6, 8]  slots [5, 6, 8, 9]  head 3

In the last lines the queue [9, 5, 6, 8] starts at slot 3 and continues at slots 0, 1 and 2. The animation draws the queue as a line from front to back, which is the queue column; the slots column is how the buffer really stores it.

Note: Many textbook versions keep head\textit{head} and tail\textit{tail} instead of a count and leave one slot always empty, because with two indices alone "empty" (head=tail\textit{head} = \textit{tail}) and "full" would look the same. Keeping size\textit{size} avoids the wasted slot.

In C++

The C++ version is a class template with the same three fields. It checks itself against std::queue (an adapter over std::deque) on 100,000 random operations with a fixed seed.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <queue>
#include <random>
#include <stdexcept>
#include <vector>

template <typename T>
class RingQueue {
    std::vector<T> a_;
    std::size_t head_ = 0, size_ = 0;
public:
    explicit RingQueue(std::size_t m) : a_(m) {}
    bool full() const { return size_ == a_.size(); }
    bool empty() const { return size_ == 0; }
    void enqueue(const T& x) {
        if (full()) throw std::overflow_error("queue overflow");
        a_[(head_ + size_) % a_.size()] = x;
        ++size_;
    }
    T dequeue() {
        if (empty()) throw std::underflow_error("queue underflow");
        T x = a_[head_];
        head_ = (head_ + 1) % a_.size();
        --size_;
        return x;
    }
};

int main() {
    RingQueue<int> q(8);
    std::queue<int> ref;
    std::mt19937 rng(2024);
    long ops = 0, maxSize = 0;
    for (int step = 0; step < 100000; ++step) {
        if (!q.full() && (q.empty() || rng() % 2 == 0)) {
            int x = static_cast<int>(rng() % 1000);
            q.enqueue(x); ref.push(x);
        } else {
            int x = q.dequeue();
            if (x != ref.front()) { std::printf("mismatch at step %d\n", step); return 1; }
            ref.pop();
        }
        ++ops;
        maxSize = std::max(maxSize, static_cast<long>(ref.size()));
    }
    std::printf("%ld operations agree with std::queue; largest size %ld of 8 slots\n", ops, maxSize);
}
100000 operations agree with std::queue; largest size 8 of 8 slots

A queue from two stacks

A different construction shows an idea that returns in the amortized-analysis lessons. Keep two stacks, inbox and outbox. ENQUEUE pushes onto inbox. DEQUEUE pops from outbox; if outbox is empty, first move everything from inbox to outbox, which reverses the order, so the oldest element ends on top.

A single DEQUEUE can cost Θ(n)\Theta(n) moves, but each element is moved from inbox to outbox at most once in its life. So nn operations cost O(n)O(n) in total, O(1)O(1) amortized per operation. The program counts the moves.

python · try it yourself
import random

class TwoStackQueue:
    def __init__(self):
        self.inbox, self.outbox, self.moves = [], [], 0
    def enqueue(self, x):
        self.inbox.append(x)
    def dequeue(self):
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop())
                self.moves += 1
        return self.outbox.pop()

rng = random.Random(5)
q, ref, worst = TwoStackQueue(), [], 0
ops = 0
for step in range(20000):
    if ref and rng.random() < 0.45:
        before = q.moves
        assert q.dequeue() == ref.pop(0)
        worst = max(worst, q.moves - before)
    else:
        x = rng.randrange(1000)
        q.enqueue(x); ref.append(x)
    ops += 1
print(f"{ops} operations, {q.moves} moves in total ({q.moves / ops:.2f} per operation)")
print(f"most moves in a single dequeue: {worst}")
20000 operations, 10878 moves in total (0.54 per operation)
most moves in a single dequeue: 1936

One dequeue moved almost two thousand elements, yet the average stays below one move per operation. This "expensive now, but paid for by earlier cheap steps" pattern is what amortized analysis makes precise.

In practice: Python's collections.deque is a doubly linked list of fixed-size blocks; it gives O(1)O(1) appends and pops at both ends, so use it rather than list.pop(0), which shifts every element. C++'s std::deque is an array of blocks with a similar guarantee.

Test yourself

A circular buffer has m=5m = 5 slots, head=3head = 3 and size=4size = 4. Where does the next ENQUEUE write?

  1. slot 0
  2. slot 2
  3. slot 7
  4. nowhere: the buffer is full

Why is DEQUEUE with list.pop(0) on a Python list a poor queue?

  1. It returns the wrong element
  2. It shifts all remaining elements left, so it costs Θ(n)\Theta(n)
  3. It is not allowed on lists
  4. It reverses the list

In the queue built from two stacks, how many times can one element be moved from inbox to outbox?

  1. at most once
  2. at most twice
  3. once per DEQUEUE
  4. up to nn times