data structureslinear

stack + queue

a stack hands back the newest item, a queue the oldest. one ring buffer does both.

report a mistake
.md

the items stay put. a head index and a size mark the ends, and the slots wrap around.

push
O(1) amortized, at either end
pop
O(1) at either end
peek / get(i)
O(1) (head + i) % capacity
grow
O(n) copies everything, once per doubling
insert in the middle
O(n) only the ends are cheap
reach for it
  • undo history
  • matching brackets
  • a bfs frontier
  • task queues
  • sliding windows
on this page
  1. the idea
  2. the easy part
  3. the operations
  4. try it
  5. pseudocode
  6. the wrap and the grow, up close
  7. complexity
  8. implementations
  9. pitfalls
  10. variants
  11. practice
  12. how real libraries do it
  13. sources

a stack and a queue hold the same items in the same order. the difference is the end you take from: a stack hands back the newest item first (last in, first out: lifo), a queue the oldest (first in, first out: fifo). one array with a moving head and a size does both.

the idea

four items go in. take them back out from each end, then see why the front is slow on a plain array, and what fixes it:

four items arrive in order: 1, 2, 3, 4.

an animation in six steps. four items, 1 to 4, arrive in a row. stacked up, the newest, 4, comes off the top first. lined up as a queue, the oldest, 1, leaves first. then the four sit in a row of six slots: taking 1 from the front shifts 2, 3 and 4 left one slot each, 3 moves. put back, the same pop instead moves a cyan head index from slot 0 to slot 1, 0 moves, while an amber tail marks the next free slot. 5 and 6 fill the last two slots, the tail wraps around to slot 0, and the row bends into a ring.

the easy part

a stack is an array and a count. the count is also the top, the next free slot: push writes there and adds 1, pop subtracts 1 and hands back what’s there. nothing else moves, so both are O(1). push is amortized, since a full array has to grow first.

a queue on a plain array is the trap. a pop takes from the front, slot 0, and every item behind it shifts left one slot to close the gap: O(n) per pop. python’s list.pop(0) works this way, and the python tutorial sends queues to collections.deque instead.1

the operations

in

the ring: 4 slots, 0 used

0headtail
1
2
3
out

push a few items in, then take some out. watch the head and the tail.

moves this step
0
all pushes
0 moves for 0
pseudocode
push_back(d, x):  if d.size == d.cap: grow(d)  d.slots[(d.head + d.size) % d.cap] = x  # tail: the next free slot  d.size += 1 push_front(d, x):  if d.size == d.cap: grow(d)  d.head = (d.head - 1 + d.cap) % d.cap  # + cap keeps it from going negative  d.slots[d.head] = x  d.size += 1 pop_front(d):  if d.size == 0: error "empty"  x = d.slots[d.head]  d.head = (d.head + 1) % d.cap  d.size -= 1  return x pop_back(d):  if d.size == 0: error "empty"  d.size -= 1  return d.slots[(d.head + d.size) % d.cap] grow(d):  # double, and unwrap so the front sits at slot 0  bigger = array of 2 * d.cap empty slots  for i in range(d.size):    bigger[i] = d.slots[(d.head + i) % d.cap]  d.slots, d.cap, d.head = bigger, 2 * d.cap, 0

an interactive ring buffer that starts with 4 slots. buttons push, pop and peek at the front and the back, and a mode switch (stack, queue, deque) picks which ends you can use, over the same state. the head slot is cyan, the tail amber, the matching pseudocode line is highlighted, and a counter tracks the items moved. a push into a full ring doubles the slots and copies the items over in order, so the front lands at slot 0.

stack, queue and deque share one ring: stack uses only the back, queue pushes at the back and pops at the front, deque uses both ends. head is cyan, tail is amber, and the pseudocode follows along. in queue mode, fill the ring, pop twice, and push twice: the new items wrap into slots 0 and 1. push once more and the full ring doubles and unwraps.

try it

3, then 7, then 5 go onto a stack. which comes off first?

375

pick one.

0 / 0 right

a practice exercise. first: which item comes off a stack, and which leaves a queue. then a ring with its slots, head and tail, and an operation like push front or pop back: pick the slot it writes to or takes from. some answers wrap past the end, and for a push into a full ring you pick the slot in the doubled ring.

run the operation in your head, pick the slot, then check. a few of them wrap.

pseudocode

pseudocode
push_back(d, x):
  if d.size == d.cap: grow(d)
  d.slots[(d.head + d.size) % d.cap] = x  # tail: the next free slot
  d.size += 1

push_front(d, x):
  if d.size == d.cap: grow(d)
  d.head = (d.head - 1 + d.cap) % d.cap  # + cap keeps it from going negative
  d.slots[d.head] = x
  d.size += 1

pop_front(d):
  if d.size == 0: error "empty"
  x = d.slots[d.head]
  d.head = (d.head + 1) % d.cap
  d.size -= 1
  return x

pop_back(d):
  if d.size == 0: error "empty"
  d.size -= 1
  return d.slots[(d.head + d.size) % d.cap]

grow(d):  # double, and unwrap so the front sits at slot 0
  bigger = array of 2 * d.cap empty slots
  for i in range(d.size):
    bigger[i] = d.slots[(d.head + i) % d.cap]
  d.slots, d.cap, d.head = bigger, 2 * d.cap, 0

d.cap is the number of slots. there’s no tail field: (d.head + d.size) % d.cap is the next free slot at the back, and pop_back shrinks the size first, so the same formula then lands on the last item.

the wrap and the grow, up close

complexity

operationworstamortized
push, either endO(n)O(1)
pop, either endO(1)O(1)
peek / get(i)O(1)O(1)
insert in the middleO(n)O(n)

a push’s worst case is the one that finds the ring full and copies everything. there’s no average case to list: nothing here is random, so the same operations always cost the same.

space is O(n) for the most items the ring has ever held: it never shrinks. sedgewick and wayne’s queue halves its array when it drops to a quarter full, so its space follows the current size.7

03161push 1push 64
64 pushes
124 moves
per push
1.94
a push that grows
average so far

a chart of 64 pushes into a ring that starts with 4 slots. each push costs 1 move for its write, and a push that finds the ring full also copies every item, so the chart spikes there, in amber. a white line tracks the average cost so far. a picker switches the growth rule between double it, grow by half and add 4 slots: doubling ends at 124 moves, under 2 per push, while adding 4 slots climbs to 544, 8.5 per push.

why a push is O(1) amortized: a grow that copies k items happens on the push that finds the ring full. since the last grow (or the start), the ring went from at most half full to full, so at least k/2 pushes came in between. charge each of those pushes 2 extra moves and the copy is paid for before it happens. every push then costs at most 3 moves: its own write, plus 2 saved up.

the same thing as a sum: the grows copy 4, 8, 16, … items, each twice the one before. a sum like that is less than twice its last term, and the last grow copied fewer than n items, so n pushes cost under 2n copies.

growing by half works too, with a bigger constant. java’s ArrayDeque does that once it’s big.2 adding a fixed number of slots doesn’t: the copies add up to O(n²).

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded pushes and pops checked against a plain array or the language’s own deque. an empty pop or peek is where they differ: go returns false as a second value, rust returns None, typescript undefined, c returns false, swift nil, and python raises IndexError.

go/algos/ringdeque/ringdeque.go
// Package ringdeque is a reference ring-buffer deque:
// O(1) push and pop at both ends (push is amortized). doubles and unwraps when full.
package ringdeque

// Deque is a double-ended queue on a ring buffer. the tail isn't stored:
// the next free slot at the back is (head + size) % len(slots).
// make one with New: the zero value has no slots, so pushing to it panics.
type Deque[T any] struct {
	slots []T
	head  int // where the front item sits
	size  int // head == tail means empty or full, so the size tells them apart
}

// New returns an empty deque with room for 4 items.
func New[T any]() *Deque[T] {
	return &Deque[T]{slots: make([]T, 4)}
}

// Len returns how many items are in the deque.
func (d *Deque[T]) Len() int {
	return d.size
}

// Cap returns how many items fit before the next grow.
func (d *Deque[T]) Cap() int {
	return len(d.slots)
}

// PushBack adds x at the back, growing first if the ring is full.
func (d *Deque[T]) PushBack(x T) {
	if d.size == len(d.slots) {
		d.grow()
	}
	d.slots[(d.head+d.size)%len(d.slots)] = x
	d.size++
}

// PushFront adds x at the front, growing first if the ring is full.
func (d *Deque[T]) PushFront(x T) {
	if d.size == len(d.slots) {
		d.grow()
	}
	// + len(d.slots) keeps it from going negative: in go, -1 % 4 is -1, not 3
	d.head = (d.head - 1 + len(d.slots)) % len(d.slots)
	d.slots[d.head] = x
	d.size++
}

// PopFront removes and returns the front item, or false if the deque is empty.
func (d *Deque[T]) PopFront() (T, bool) {
	var zero T
	if d.size == 0 {
		return zero, false
	}
	x := d.slots[d.head]
	d.slots[d.head] = zero // clear the slot so it doesn't hold on to the item
	d.head = (d.head + 1) % len(d.slots)
	d.size--
	return x, true
}

// PopBack removes and returns the back item, or false if the deque is empty.
func (d *Deque[T]) PopBack() (T, bool) {
	var zero T
	if d.size == 0 {
		return zero, false
	}
	d.size--
	i := (d.head + d.size) % len(d.slots)
	x := d.slots[i]
	d.slots[i] = zero
	return x, true
}

// PeekFront returns the front item without removing it, or false if the deque is empty.
func (d *Deque[T]) PeekFront() (T, bool) {
	if d.size == 0 {
		var zero T
		return zero, false
	}
	return d.slots[d.head], true
}

// PeekBack returns the back item without removing it, or false if the deque is empty.
func (d *Deque[T]) PeekBack() (T, bool) {
	if d.size == 0 {
		var zero T
		return zero, false
	}
	return d.slots[(d.head+d.size-1)%len(d.slots)], true
}

// Get returns the item i places from the front, or false if i is past either end.
func (d *Deque[T]) Get(i int) (T, bool) {
	if i < 0 || i >= d.size {
		var zero T
		return zero, false
	}
	return d.slots[(d.head+i)%len(d.slots)], true
}

// grow doubles the slots and copies the items over in order, so the front lands at slot 0.
func (d *Deque[T]) grow() {
	bigger := make([]T, 2*len(d.slots))
	for i := range d.size {
		bigger[i] = d.slots[(d.head+i)%len(d.slots)]
	}
	d.slots = bigger
	d.head = 0
}
rust/algos/src/ring_deque.rs
//! ring-buffer deque: O(1) push and pop at both ends (push is amortized). doubles and unwraps when full.

/// A double-ended queue on a ring buffer. It starts with 4 slots and never shrinks.
/// The tail, the next free slot at the back, isn't stored: it's `(head + len) % capacity`.
pub struct RingDeque<T> {
    slots: Vec<Option<T>>, // None is a free slot
    head: usize,           // where the front item sits
    len: usize,            // head == tail means empty or full, so len tells them apart
}

impl<T> RingDeque<T> {
    /// Makes an empty deque with 4 slots.
    pub fn new() -> Self {
        let mut slots = Vec::new();
        slots.resize_with(4, || None); // vec![None; 4] would need T: Clone
        Self {
            slots,
            head: 0,
            len: 0,
        }
    }

    /// The number of items.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no items.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The number of slots: how many items fit before the next grow.
    pub fn capacity(&self) -> usize {
        self.slots.len()
    }

    /// Adds `item` at the back. Grows first if every slot is full.
    pub fn push_back(&mut self, item: T) {
        if self.len == self.capacity() {
            self.grow();
        }
        let tail = (self.head + self.len) % self.capacity();
        self.slots[tail] = Some(item);
        self.len += 1;
    }

    /// Adds `item` at the front. Grows first if every slot is full.
    pub fn push_front(&mut self, item: T) {
        if self.len == self.capacity() {
            self.grow();
        }
        // + capacity first: head is a usize, so 0 - 1 would underflow
        self.head = (self.head + self.capacity() - 1) % self.capacity();
        self.slots[self.head] = Some(item);
        self.len += 1;
    }

    /// Removes and returns the front item, or `None` if the deque is empty.
    pub fn pop_front(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }
        let item = self.slots[self.head].take(); // take() leaves None in the slot
        self.head = (self.head + 1) % self.capacity();
        self.len -= 1;
        item
    }

    /// Removes and returns the back item, or `None` if the deque is empty.
    pub fn pop_back(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }
        self.len -= 1;
        let back = (self.head + self.len) % self.capacity();
        self.slots[back].take()
    }

    /// The front item, or `None` if the deque is empty.
    pub fn peek_front(&self) -> Option<&T> {
        if self.is_empty() {
            return None;
        }
        self.slots[self.head].as_ref()
    }

    /// The back item, or `None` if the deque is empty.
    pub fn peek_back(&self) -> Option<&T> {
        if self.is_empty() {
            return None;
        }
        self.slots[(self.head + self.len - 1) % self.capacity()].as_ref()
    }

    /// The item `i` places from the front, or `None` if `i` is past the back.
    pub fn get(&self, i: usize) -> Option<&T> {
        if i >= self.len {
            return None;
        }
        self.slots[(self.head + i) % self.capacity()].as_ref()
    }

    /// Doubles the slots and moves the items over in order, so the front lands at slot 0.
    fn grow(&mut self) {
        let cap = self.capacity();
        let mut bigger = Vec::with_capacity(cap * 2);
        for i in 0..self.len {
            bigger.push(self.slots[(self.head + i) % cap].take());
        }
        bigger.resize_with(cap * 2, || None);
        self.slots = bigger;
        self.head = 0;
    }
}

impl<T> Default for RingDeque<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;

    /// The items front to back, read with `get`.
    fn contents(d: &RingDeque<i32>) -> Vec<i32> {
        (0..d.len()).map(|i| *d.get(i).unwrap()).collect()
    }

    #[test]
    fn starts_empty_with_room_for_4() {
        let mut d = RingDeque::<i32>::new();
        assert_eq!(d.len(), 0);
        assert!(d.is_empty());
        assert_eq!(d.capacity(), 4);
        assert_eq!((d.pop_front(), d.pop_back()), (None, None));
        assert_eq!((d.peek_front(), d.peek_back()), (None, None));
    }

    #[test]
    fn as_a_stack_the_newest_comes_out_first() {
        let mut d = RingDeque::new();
        for x in [1, 2, 3] {
            d.push_back(x);
        }
        let popped = [d.pop_back(), d.pop_back(), d.pop_back()];
        assert_eq!(popped, [Some(3), Some(2), Some(1)]);
    }

    #[test]
    fn as_a_queue_the_oldest_comes_out_first() {
        let mut d = RingDeque::new();
        for x in [1, 2, 3] {
            d.push_back(x);
        }
        let popped = [d.pop_front(), d.pop_front(), d.pop_front()];
        assert_eq!(popped, [Some(1), Some(2), Some(3)]);
    }

    #[test]
    fn both_ends() {
        let mut d = RingDeque::new();
        d.push_front(1);
        d.push_front(2);
        d.push_back(3);
        assert_eq!(contents(&d), [2, 1, 3]);
        assert_eq!((d.peek_front(), d.peek_back()), (Some(&2), Some(&3)));
    }

    #[test]
    fn wraps_around_without_growing() {
        let mut d = RingDeque::new();
        for x in [1, 2, 3, 4] {
            d.push_back(x);
        }
        d.pop_front();
        d.pop_front();
        d.push_back(5);
        d.push_back(6);
        assert_eq!(d.capacity(), 4);
        assert_eq!(contents(&d), [3, 4, 5, 6]);
    }

    #[test]
    fn grows_and_unwraps_when_full() {
        let mut d = RingDeque::new();
        for x in [1, 2, 3, 4] {
            d.push_back(x);
        }
        d.pop_front();
        d.pop_front();
        d.push_back(5);
        d.push_back(6);
        d.push_back(7);
        assert_eq!(d.capacity(), 8);
        assert_eq!(contents(&d), [3, 4, 5, 6, 7]);
    }

    #[test]
    fn doubles_each_time_it_fills() {
        let mut d = RingDeque::new();
        for x in 1..=9 {
            d.push_back(x);
        }
        // 4, 8, 16: adding 4 slots each time would stop at 12
        assert_eq!(d.capacity(), 16);
        assert_eq!(contents(&d), (1..=9).collect::<Vec<_>>());
    }

    #[test]
    fn push_front_into_a_full_ring_grows_too() {
        let mut d = RingDeque::new();
        for x in [1, 2, 3, 4] {
            d.push_back(x);
        }
        d.push_front(0);
        assert_eq!(d.capacity(), 8);
        assert_eq!(contents(&d), [0, 1, 2, 3, 4]);
    }

    #[test]
    fn get_past_the_end() {
        let mut d = RingDeque::new();
        d.push_back(1);
        // i is a usize, so there's no negative index to try at the front
        assert_eq!((d.get(1), d.get(usize::MAX)), (None, None));
    }

    #[test]
    fn agrees_with_vecdeque_over_2000_seeded_ops() {
        // xorshift32 seeded with 42, and the top 2 bits pick the op: the same as the
        // typescript test, so both run the same 2000 ops in the same order
        let mut state: u32 = 42;
        let mut next_op = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state >> 30
        };
        let mut d = RingDeque::new();
        let mut model = VecDeque::new();
        for n in 0..2000 {
            match next_op() {
                0 => {
                    d.push_back(n);
                    model.push_back(n);
                }
                1 => {
                    d.push_front(n);
                    model.push_front(n);
                }
                2 => assert_eq!(d.pop_back(), model.pop_back()),
                _ => assert_eq!(d.pop_front(), model.pop_front()),
            }
            assert_eq!(d.len(), model.len());
        }
        assert!(d.capacity() >= model.len());
        assert_eq!(contents(&d), Vec::from(model));
    }
}
site/src/visuals/stack-queue/ring-deque.ts
/**
 * Ring-buffer deque: O(1) push and pop at both ends, amortized for push.
 * Doubles and unwraps when full. The tail isn't stored: it's (head + size) % capacity.
 */
export class RingDeque<T> {
  #slots: (T | undefined)[] = new Array(4);
  #head = 0; // where the front item sits
  #size = 0; // head == tail means empty or full, so the size tells them apart

  get length(): number {
    return this.#size;
  }

  get capacity(): number {
    return this.#slots.length;
  }

  pushBack(item: T): void {
    if (this.#size === this.capacity) this.#grow();
    this.#slots[(this.#head + this.#size) % this.capacity] = item;
    this.#size += 1;
  }

  pushFront(item: T): void {
    if (this.#size === this.capacity) this.#grow();
    this.#head = (this.#head - 1 + this.capacity) % this.capacity; // + capacity keeps it from going negative
    this.#slots[this.#head] = item;
    this.#size += 1;
  }

  popFront(): T | undefined {
    if (this.#size === 0) return undefined;
    const item = this.#slots[this.#head];
    this.#slots[this.#head] = undefined;
    this.#head = (this.#head + 1) % this.capacity;
    this.#size -= 1;
    return item;
  }

  popBack(): T | undefined {
    if (this.#size === 0) return undefined;
    this.#size -= 1;
    const i = (this.#head + this.#size) % this.capacity;
    const item = this.#slots[i];
    this.#slots[i] = undefined;
    return item;
  }

  peekFront(): T | undefined {
    return this.#size === 0 ? undefined : this.#slots[this.#head];
  }

  peekBack(): T | undefined {
    return this.#size === 0 ? undefined : this.#slots[(this.#head + this.#size - 1) % this.capacity];
  }

  /** The item i places from the front, or undefined past either end. */
  get(i: number): T | undefined {
    if (!Number.isInteger(i) || i < 0 || i >= this.#size) return undefined;
    return this.#slots[(this.#head + i) % this.capacity];
  }

  /** Double the slots and copy the items over in order, so the front lands at slot 0. */
  #grow(): void {
    const bigger = new Array<T | undefined>(this.capacity * 2);
    for (let i = 0; i < this.#size; i++) bigger[i] = this.#slots[(this.#head + i) % this.capacity];
    this.#slots = bigger;
    this.#head = 0;
  }
}
c/algos/ring_deque.c
/* ring-buffer deque: O(1) push and pop at both ends (push is amortized). doubles and unwraps when full. */
#include "ring_deque.h"

#include <stdlib.h>

bool deque_init(RingDeque *d) {
    d->slots = malloc(4 * sizeof *d->slots);
    d->head = d->len = 0;
    d->cap = d->slots ? 4 : 0;
    return d->slots != NULL;
}

void deque_free(RingDeque *d) {
    free(d->slots);
    d->slots = NULL;
    d->head = d->len = d->cap = 0;
}

/* doubles the slots and copies the items over in order, so the front lands at slot 0 */
static bool grow(RingDeque *d) {
    int *bigger = malloc(2 * d->cap * sizeof *bigger);
    if (!bigger) return false; /* d is untouched, so nothing is lost */
    for (size_t i = 0; i < d->len; i++) bigger[i] = d->slots[(d->head + i) % d->cap];
    free(d->slots);
    d->slots = bigger;
    d->head = 0;
    d->cap *= 2;
    return true;
}

bool deque_push_back(RingDeque *d, int x) {
    if (d->len == d->cap && !grow(d)) return false;
    /* the back isn't stored: the next free slot there is always (head + len) % cap */
    d->slots[(d->head + d->len) % d->cap] = x;
    d->len++;
    return true;
}

bool deque_push_front(RingDeque *d, int x) {
    if (d->len == d->cap && !grow(d)) return false;
    /* one slot back, 0 wrapping to cap - 1. + cap comes first, since a size_t can't go below 0 */
    d->head = (d->head + d->cap - 1) % d->cap;
    d->slots[d->head] = x;
    d->len++;
    return true;
}

/* pops leave the old int in its slot: there's nothing to free, and a later push writes over it */
bool deque_pop_back(RingDeque *d, int *out) {
    if (d->len == 0) return false;
    d->len--;
    *out = d->slots[(d->head + d->len) % d->cap];
    return true;
}

bool deque_pop_front(RingDeque *d, int *out) {
    if (d->len == 0) return false;
    *out = d->slots[d->head];
    d->head = (d->head + 1) % d->cap;
    d->len--;
    return true;
}

bool deque_peek_front(const RingDeque *d, int *out) {
    if (d->len == 0) return false;
    *out = d->slots[d->head];
    return true;
}

bool deque_peek_back(const RingDeque *d, int *out) {
    if (d->len == 0) return false;
    *out = d->slots[(d->head + d->len - 1) % d->cap];
    return true;
}

bool deque_get(const RingDeque *d, size_t i, int *out) {
    if (i >= d->len) return false; /* a size_t can't be negative, so this covers both ends */
    *out = d->slots[(d->head + i) % d->cap];
    return true;
}
swift/algos/RingDeque.swift
/// ring-buffer deque: O(1) push and pop at both ends (push is amortized). doubles and unwraps when full.
/// the tail isn't stored: the next free slot at the back is (head + count) % capacity.
public struct RingDeque<Element> {
    private var slots = [Element?](repeating: nil, count: 4)
    private var head = 0 // where the front item sits
    // head == tail means empty or full, so the count tells them apart
    public private(set) var count = 0

    public init() {}

    public var capacity: Int { slots.count }

    public mutating func pushBack(_ item: Element) {
        if count == capacity { grow() }
        slots[(head + count) % capacity] = item
        count += 1
    }

    public mutating func pushFront(_ item: Element) {
        if count == capacity { grow() }
        // + capacity keeps it from going negative: swift's % keeps the sign, so -1 % 4 is -1
        head = (head - 1 + capacity) % capacity
        slots[head] = item
        count += 1
    }

    public mutating func popFront() -> Element? {
        guard count > 0 else { return nil }
        let item = slots[head]
        slots[head] = nil // clear the slot so it doesn't hold on to the item
        head = (head + 1) % capacity
        count -= 1
        return item
    }

    public mutating func popBack() -> Element? {
        guard count > 0 else { return nil }
        count -= 1
        let i = (head + count) % capacity
        let item = slots[i]
        slots[i] = nil
        return item
    }

    public func peekFront() -> Element? {
        count == 0 ? nil : slots[head]
    }

    public func peekBack() -> Element? {
        count == 0 ? nil : slots[(head + count - 1) % capacity]
    }

    /// the item i places from the front, or nil past either end.
    public func get(_ i: Int) -> Element? {
        guard i >= 0 && i < count else { return nil }
        return slots[(head + i) % capacity]
    }

    /// doubles the slots and copies the items over in order, so the front lands at slot 0.
    private mutating func grow() {
        var bigger = [Element?](repeating: nil, count: capacity * 2)
        for i in 0..<count {
            bigger[i] = slots[(head + i) % capacity]
        }
        slots = bigger
        head = 0
    }
}
python/algos/ring_deque.py
"""ring-buffer deque: O(1) push and pop at both ends (push is amortized). doubles and unwraps when full."""

from __future__ import annotations

from typing import Any, Generic, TypeVar

T = TypeVar("T")


class RingDeque(Generic[T]):
    """A ring-buffer deque. The tail isn't stored: it's (head + size) % capacity."""

    def __init__(self) -> None:
        self._slots: list[Any] = [None] * 4  # free slots hold None
        self._head = 0  # where the front item sits
        self._size = 0  # head == tail means empty or full, so the size tells them apart

    def __len__(self) -> int:
        return self._size

    @property
    def capacity(self) -> int:
        return len(self._slots)

    def push_back(self, item: T) -> None:
        if self._size == self.capacity:
            self._grow()
        self._slots[(self._head + self._size) % self.capacity] = item
        self._size += 1

    def push_front(self, item: T) -> None:
        if self._size == self.capacity:
            self._grow()
        # the + capacity matters in c, go, rust and swift. python's -1 % 4 is already 3
        self._head = (self._head - 1 + self.capacity) % self.capacity
        self._slots[self._head] = item
        self._size += 1

    def pop_front(self) -> T:
        if self._size == 0:
            raise IndexError("pop from an empty deque")
        item = self._slots[self._head]
        self._slots[self._head] = None  # drop the reference so the item can be freed
        self._head = (self._head + 1) % self.capacity
        self._size -= 1
        return item

    def pop_back(self) -> T:
        if self._size == 0:
            raise IndexError("pop from an empty deque")
        self._size -= 1
        i = (self._head + self._size) % self.capacity
        item = self._slots[i]
        self._slots[i] = None
        return item

    def peek_front(self) -> T:
        if self._size == 0:
            raise IndexError("peek at an empty deque")
        return self._slots[self._head]

    def peek_back(self) -> T:
        if self._size == 0:
            raise IndexError("peek at an empty deque")
        return self._slots[(self._head + self._size - 1) % self.capacity]

    def get(self, i: int) -> T:
        """Return the item i places from the front.

        Raises IndexError past either end. Unlike a list, -1 is past the front.
        """
        if not 0 <= i < self._size:
            raise IndexError("deque index out of range")
        return self._slots[(self._head + i) % self.capacity]

    def _grow(self) -> None:
        """Double the slots. Copy the items in order, so the front lands at slot 0."""
        bigger = [None] * (2 * self.capacity)
        for i in range(self._size):
            bigger[i] = self._slots[(self._head + i) % self.capacity]
        self._slots = bigger
        self._head = 0

pitfalls

variants

practice

how real libraries do it

sources

  1. the python tutorial, using lists as queues (opens in a new tab): pops at the end of a list are fast, but at the front every other item shifts over by one. the docs’ time complexity (opens in a new tab) page puts pop(k) at O(n - k), worst at index 0. ↩ ↩2

  2. ArrayDeque (opens in a new tab) in the java 21 docs, and its source (opens in a new tab) at jdk-21-ga: a circular array with head and tail, at least one empty slot, inc and dec that compare instead of dividing, and a grow that doubles small arrays and adds half to big ones. ↩ ↩2 ↩3 ↩4 ↩5

  3. how % treats a negative left side: c’s draft standard n1570 (opens in a new tab), 6.5.5 paragraph 6; integer operators (opens in a new tab) in the go spec; arithmetic operators (opens in a new tab) in the rust reference; the remainder operator (opens in a new tab) in the swift book; Number::remainder (opens in a new tab) in the ecmascript spec, which typescript compiles to; and python’s binary arithmetic operations (opens in a new tab). ↩ ↩2

  4. overflow (opens in a new tab) in the rust reference: integer operators panic on overflow in a debug build. for c, n1570 (opens in a new tab) 6.2.5 paragraph 9: unsigned arithmetic never overflows, it wraps around modulo one more than the largest value. ↩ ↩2

  5. _collectionsmodule.c (opens in a new tab) in cpython 3.15.0: the deque is a doubly linked list of 64-slot blocks, so appends and pops never move other items and it never calls realloc. the block length is a power of two to speed up the index math. ↩ ↩2

  6. VecDeque (opens in a new tab) in the rust docs, and its source (opens in a new tab) at 1.99.1: a head and a len, a wrap_index that subtracts the capacity instead of dividing, and a handle_capacity_increase that moves the shorter wrapped section after a grow. ↩ ↩2

  7. ResizingArrayQueue.java (opens in a new tab) from sedgewick and wayne’s algorithms, 4th edition: a ring that doubles when full, halves at a quarter full, and sets each popped slot to null so it doesn’t loiter. ↩ ↩2

  8. collections.deque (opens in a new tab) in the python docs: O(1) appends and pops at either end, O(n) indexing in the middle, and maxlen, which drops items off the other end once the deque is full. ↩ ↩2 ↩3

  9. printk basics (opens in a new tab) and /dev/kmsg (opens in a new tab) in the linux docs at v7.2: the kernel log buffer is a ring buffer, and messages in it get overwritten. ↩

  10. go’s standard library (opens in a new tab) at go1.27.2, with container/list (opens in a new tab) and container/ring (opens in a new tab). neither the package list nor the exported api (opens in a new tab) has a deque. ↩

  11. runtime/chan.go (opens in a new tab) at go1.27.2: hchan holds a count, the size of its circular queue, a buffer, and send and receive indexes that go back to 0 at the end. ↩

  12. Deque.swift (opens in a new tab) in swift-collections 1.7.3: the deque keeps its items in a circular buffer, so its storage may not be contiguous. ↩