Skip to content
Visual explainer 3h to learn 4 steps

Queues, circular buffers & deques

Implement a queue with a circular buffer and choose between queue and deque for a problem.

By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.

Topic 13 of 54

In short

A queue is first-in, first-out: enqueue at the back, dequeue at the front. A circular buffer implements it on a fixed array by wrapping indexes with modulo. A deque allows O(1) pushes and pops at both ends, which powers BFS and sliding window maximum.

Explained simply

A queue works like a line at a ticket counter. People join at the back and leave from the front, so the first to arrive is the first to be served. This is called FIFO: first in, first out.

Queues are everywhere in software. A printer queue, messages waiting to be processed, web requests waiting for a worker, and the breadth-first search algorithm all use the same idea: handle things in the order they arrived.

The obvious way to build a queue in Python, a list with append and pop(0), is a trap. Removing from the front of a list moves every remaining item one step to the left, so it gets slower as the queue grows.

The right tools are collections.deque, a double-ended queue that is fast at both ends, and the ring buffer, a fixed-size array whose ends wrap around in a circle. Both add and remove items in constant time.

Press Play on a diagram to walk through it one step at a time.

CompareQueue implementations in Python
list with pop(0)
  • Dequeue is O(n)
  • Shifts every element
  • Avoid for queues
collections.deque
  • append and popleft O(1)
  • Both ends supported
  • Default choice
Ring buffer
  • Fixed capacity array
  • head and tail wrap with modulo
  • Used in OS and networking
MapWhich queue-like tool to use in Python
Items wait their turn
  • Oldest first (FIFO)
    • collections.deque
    • append + popleft
  • Both ends needed
    • collections.deque
    • Sliding windows, 0-1 BFS
  • Most important first
    • heapq
    • O(log n) push and pop
  • Between threads
    • queue.Queue
    • Blocking get and put
  • Fixed memory
    • Ring buffer
    • Or deque(maxlen=k)

In depth

Why list.pop(0) is O(n)

A Python list stores pointers to its items in one contiguous block of memory, and item i must always be in slot i. When you remove item 0, the list moves every other pointer one slot to the left to close the gap. For a list of n items that is n - 1 moves, so pop(0) is O(n). insert(0, x) does the same in the other direction.

For a few items you will not notice. For a BFS over a million nodes, using pop(0) does about n squared over 2 pointer moves in total, which turns a fast O(V + E) algorithm into one that takes minutes.

The fix is a structure that can drop items from the front without moving the rest. A ring buffer just advances a head index. A deque keeps its items in linked blocks and frees a block once it is empty.

  • list.pop(0): O(n)
  • list.pop(): O(1)
  • deque.popleft(): O(1)

The ring buffer: a queue in a fixed array

A ring buffer is an array of fixed capacity plus two numbers: head, the index of the front item, and count, how many items are stored. The back slot is (head + count) % capacity. Enqueue writes there and increases count. Dequeue reads buf[head], moves head to (head + 1) % capacity and decreases count. The modulo makes the indexes wrap from the last slot back to slot 0, so the array is used in a circle and nothing ever shifts.

The classic trap is telling full from empty. If you only store head and tail indexes, head == tail can mean either. Two fixes are common: keep a count, as here, or always leave one slot unused so full means (tail + 1) % capacity == head.

Ring buffers have fixed memory and no allocation, which is why they are used in audio, network cards, logging and kernels. To grow one, allocate a bigger array and copy the items in order from head, unwrapping them.

CycleRing buffer of capacity 4: indexes wrap around
  1. 1
    Enqueue a, b, c

    Slots 0, 1, 2; head 0, count 3

  2. 2
    Dequeue twice

    a and b leave; head 2, count 1

  3. 3
    Enqueue d, e

    d in slot 3, e wraps to slot 0

  4. 4
    Enqueue f

    Slot 1; count 4: the buffer is full

  5. 5
    Dequeue

    c leaves from slot 2; head moves to 3

  6. Back to step 1

Inside collections.deque

CPython's deque is a doubly linked list of fixed-size blocks, each holding 64 items. Appending or popping at either end touches only the end block and allocates or frees a block now and then, so append, appendleft, pop and popleft are all O(1). Because items live in blocks, it has far fewer pointers and better memory locality than a linked list of single nodes.

The cost is indexing. The documentation states that indexed access is O(1) at both ends but slows to O(n) in the middle, because deque must walk through blocks. So use a deque for its ends, not as a general array.

Two useful features: deque(maxlen=k) keeps only the last k items, dropping from the opposite end when full, which is perfect for recent history or tail -n. rotate(n) moves items from one end to the other. deque operations at the ends are also thread-safe, though queue.Queue is the better tool for producer and consumer threads because it can block and wait.

  • append, appendleft, pop, popleft: O(1)
  • dq[i] near the middle: O(n)
  • deque(maxlen=k): bounded, drops the oldest

Choosing between queue, deque and the others

Use a plain FIFO queue (deque with append and popleft) when items must be handled in arrival order: BFS, task scheduling, buffering.

Use a deque when you need both ends. The sliding window maximum in the explainer pushes new indexes at the back, pops dominated ones from the back and expired ones from the front. 0-1 BFS, a shortest-path trick for edges of weight 0 or 1, pushes weight-0 neighbours at the front and weight-1 neighbours at the back.

Use a priority queue (heapq) when the most important item should leave first rather than the oldest. That is not FIFO, and push and pop cost O(log n).

For threads, queue.Queue gives blocking put and get with an optional maximum size. For asyncio code, asyncio.Queue does the same for coroutines. Neither is needed for single-threaded algorithms, and both are slower than a deque.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Implement a ring buffer queue~45m
  2. 2
    Explain why list.pop(0) is O(n)~45m
  3. 3
    Use collections.deque at both ends~45m
  4. 4
    Build a sliding window maximum with a deque~45m

Key points

  • Enqueue and dequeue: O(1) with deque or a ring buffer.
  • Ring buffer index: (head + count) % capacity.
  • Sliding window maximum runs in O(n) with a monotonic deque of indexes.
  • queue.Queue adds thread-safety; it is not needed for algorithms.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
from collections import deque

def window_max(nums, k):          # O(n)
    dq, out = deque(), []         # dq holds indexes, values decreasing
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

print(window_max([1, 3, -1, -3, 5, 3], 3))  # [3, 3, 5, 5]

A ring buffer queue with fixed capacity

Goal: a queue that never allocates after creation. Step 1: create the array, head = 0 and count = 0. Step 2: enqueue computes the back slot with modulo and refuses when count equals capacity. Step 3: dequeue reads the head slot, clears it so the object can be freed, and advances head with modulo. Both operations are O(1), and keeping count makes full and empty easy to tell apart.

python
class RingQueue:
    def __init__(self, capacity):
        self.buf, self.head, self.count = [None] * capacity, 0, 0
    def enqueue(self, x):                       # O(1)
        if self.count == len(self.buf):
            raise OverflowError("queue full")
        self.buf[(self.head + self.count) % len(self.buf)] = x
        self.count += 1
    def dequeue(self):                          # O(1)
        if self.count == 0:
            raise IndexError("queue empty")
        x, self.buf[self.head] = self.buf[self.head], None
        self.head = (self.head + 1) % len(self.buf)
        self.count -= 1
        return x

Counting requests in the last 3 seconds

A rate limiter needs to know how many requests arrived in the last 3000 ms. Step 1: append each new timestamp to the back of a deque. Step 2: pop from the front every timestamp older than t - 3000. Step 3: the deque's length is the answer. Each timestamp is appended once and removed at most once, so each call is amortised O(1).

python
from collections import deque

class RecentCounter:
    def __init__(self):
        self.q = deque()
    def ping(self, t):
        self.q.append(t)
        while self.q[0] < t - 3000:
            self.q.popleft()
        return len(self.q)

rc = RecentCounter()
print([rc.ping(t) for t in (1, 100, 3001, 3002)])  # [1, 2, 3, 3]

Quick reference

  • Queue in Python: deque.append(x) to enqueue, deque.popleft() to dequeue, both O(1)
  • list.pop(0) and list.insert(0, x) are O(n): never use them for queues
  • Ring buffer back slot: (head + count) % capacity
  • Ring buffer full vs empty: keep a count, or leave one slot unused
  • deque(maxlen=k) keeps only the last k items
  • deque indexing is O(1) at the ends but O(n) in the middle
  • queue.Queue is for threads; heapq is for priority order, not FIFO

Common mistakes

  • Using list.pop(0) in BFS, turning O(V + E) into something much slower.
  • Not distinguishing full and empty states in a ring buffer.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A ring buffer has capacity 8, head = 6 and count = 3. Which index does the next enqueue write to?

Question 2

2What is the time complexity of BFS on a graph with V vertices if you use list.pop(0) as the queue?

Question 3

3What happens when you append to a full deque(maxlen=3)?

Question 4

4In a ring buffer that stores only head and tail indexes, why is head == tail ambiguous?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the last 5 lines of a text file without reading them all into a list.

  2. Exercise 2medium

    Implement a queue using two stacks (Python lists) with amortised O(1) enqueue and dequeue.

  3. Exercise 3hard

    Find the length of the longest contiguous subarray in which max minus min is at most limit, in O(n).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a queue and a deque?
A queue adds at the back and removes from the front. A deque (double-ended queue) can add and remove at both ends, so it can act as a queue, a stack, or both.
Should I use queue.Queue for BFS?
No. queue.Queue adds locks for thread safety, which makes it slower. Use collections.deque in single-threaded algorithms.
Is collections.deque a linked list?
Partly. CPython builds it as a doubly linked list of blocks that each hold 64 items, which gives O(1) operations at both ends with good memory use.
What is a circular buffer used for in real systems?
Anywhere a fixed amount of memory must hold a stream of data: audio and video buffers, network card packet rings, kernel logs (dmesg) and lock-free queues between threads.

Go deeper

ShareXLinkedInWhatsApp