# stack + queue

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

source: https://learning.anthnydas.com/ds/stack-queue/

## tl;dr

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

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:

> **interactive figure:** 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.

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

a stack takes from the end it adds to. the newest, 4, comes off first.

a queue takes from the other end. the oldest, 1, leaves first.

on a plain array the front is always slot 0. take 1 out and 2, 3 and 4 each shift left a slot: 3 moves, so a pop from the front is O(n).

the fix: leave the items where they are and move a head index (cyan) instead. the tail (amber) is the next free slot, `head + size`. 0 moves.

5 and 6 fill the last two slots, and the tail runs off the end: it wraps to slot 0, the room 1 left behind. bend the row and it's 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.[^pylist]

## the operations

> **interactive figure:** 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

> **interactive figure:** 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

```text
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

- the tail is derived, never stored: the next free slot at the back is always `(head + size) % capacity`. one less field to keep in sync
- store the size, because `head == tail` means two things: empty, and full, when the tail has wrapped all the way around onto the head. the size tells them apart. java's `ArrayDeque` keeps one slot empty instead: it grows the moment a push fills the last one, so `head == tail` means empty[^java]
- `push_front` steps the head back one slot with `(head - 1 + capacity) % capacity`. the `+ capacity` matters. in c, go, rust, swift and typescript, `%` keeps the sign of the left side, so `-1 % 4` is `-1`, not a slot. python's `%` takes the sign of the right side, so there it's `3`[^mod]
- the c and rust tabs write `(head + capacity - 1) % capacity` instead. their indexes are unsigned, so `head - 1` at 0 isn't -1: rust panics on it in a debug build, and c wraps it around to the largest `size_t`. adding first never goes below 0[^unsigned]
- a grow copies the items in order, front first, into slots 0, 1, 2, ... of an array twice the size, then sets `head` to 0. the wrap disappears: right after a grow, the ring is a plain row again
- with power-of-two capacities, `% capacity` can become `& (capacity - 1)`: a bit mask instead of a division. this ring starts at 4 and doubles, so it always qualifies. cpython's deque keeps its block length a power of two for the same reason.[^cpython] java's and rust's deques skip the division another way: an index is never more than one lap off, so a comparison and one add or subtract puts it back in range[^java][^rust]

## complexity

| operation            | worst | amortized |
| -------------------- | ----- | --------- |
| push, either end     | O(n)  | O(1)      |
| pop, either end      | O(1)  | O(1)      |
| peek / `get(i)`      | O(1)  | O(1)      |
| insert in the middle | O(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.[^algs4]

> **interactive figure:** 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.[^java] 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`

```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`

```rust
//! 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`

```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`

```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`

```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`

```python
"""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

- **full vs empty.** with only `head` and `tail`, `head == tail` is true for an empty ring and for a full one. store the size, or keep one slot always empty like java does[^java]
- **negative modulo.** with signed indexes, `(head - 1) % capacity` at head 0 is `-1` in every language here but python, and that isn't a slot: add `capacity` first. with unsigned ones, add before you subtract[^mod][^unsigned]
- **`list.pop(0)` as a queue.** each pop shifts the whole list, so draining n items costs O(n²). `collections.deque` pops from the left in O(1)[^pylist][^deque]
- **not clearing popped slots.** in a garbage-collected language, a popped item still sitting in its slot is still referenced, so it can't be freed while it sits there. set the slot to `None`, `nil`, `undefined` or the zero value. sedgewick and wayne's code calls the leftover reference loitering.[^algs4] c's ints hold no references, so the c tab skips it
- **indexing the slots directly.** once the head has moved, `slots[i]` isn't the i-th item. use `slots[(head + i) % capacity]`, and walk `i` from 0 to `size` instead of looping over the slots

## variants

- **deque.** the ring on this page already is one: push and pop at both ends. a stack and a queue are a deque with two of its four operations left out
- **priority queue.** hands back the smallest (or largest) item instead of the oldest or newest. a ring can't find that cheaply. a [heap](/ds/heap/) can, in O(log n) per push and pop
- **monotonic stack or queue.** before a push, pop from the back every item the new one beats, so what's left stays sorted. each item goes in and out at most once, so a pass over n items is O(n). it's the trick behind sliding window maximum
- **fixed-size ring that overwrites.** no grow: when it's full, a push writes over the oldest item. good for the last n of something, like recent log lines or the last second of audio. python's `deque(maxlen=n)` drops from the far end once full,[^deque] and the linux kernel log is a ring buffer whose old messages get overwritten[^kmsg]

## practice

- [valid parentheses](https://leetcode.com/problems/valid-parentheses/): push each open bracket. a close bracket has to match the top
- [implement queue using stacks](https://leetcode.com/problems/implement-queue-using-stacks/): two stacks make a queue, amortized O(1) per operation, by the same kind of argument as the grow
- [design circular queue](https://leetcode.com/problems/design-circular-queue/): this ring with a fixed size and no grow, so a push into a full ring returns false
- [design circular deque](https://leetcode.com/problems/design-circular-deque/): the same, with both ends
- [sliding window maximum](https://leetcode.com/problems/sliding-window-maximum/): a monotonic deque. O(n) for the whole array

## how real libraries do it

- **python.** `collections.deque` isn't a ring buffer. it's a doubly linked list of blocks, 64 slots each, so appends and pops never move any other item and nothing gets reallocated.[^cpython] the trade: indexing the middle is O(n), not O(1)[^deque]
- **java.** `ArrayDeque` is a resizable circular array. it stores `head` and `tail` but no size, and keeps one slot empty so `head == tail` means empty. small arrays double, big ones grow by half[^java]
- **rust.** `VecDeque` is a growable ring buffer that stores a head index and a length, like this one. when it grows it doesn't copy the whole ring back to slot 0: it moves only whichever wrapped piece is shorter[^rust]
- **go.** no exported deque in the standard library. its container packages are `heap`, `list`, a doubly linked list, and `ring`, a circular linked list rather than a ring buffer.[^go] the runtime has a ring buffer, though: a buffered channel keeps its items in a circular queue with a send index and a receive index[^chan]
- **swift.** apple's swift-collections package has `Deque`, which keeps its items in a circular buffer[^swift]

[^pylist]: the python tutorial, [using lists as queues](https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-queues): pops at the end of a list are fast, but at the front every other item shifts over by one. the docs' [time complexity](https://docs.python.org/3/builtins/time-complexity.html#list) page puts `pop(k)` at O(n - k), worst at index 0.

[^deque]: [collections.deque](https://docs.python.org/3/library/collections.html#collections.deque) 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.

[^mod]: how `%` treats a negative left side: c's draft standard [n1570](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), 6.5.5 paragraph 6; [integer operators](https://go.dev/ref/spec#Integer_operators) in the go spec; [arithmetic operators](https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators) in the rust reference; the [remainder operator](https://docs.swift.org/latest/documentation/the-swift-programming-language/basicoperators/#Remainder-Operator) in the swift book; [Number::remainder](https://262.ecma-international.org/17.0/#sec-numeric-types-number-remainder) in the ecmascript spec, which typescript compiles to; and python's [binary arithmetic operations](https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations).

[^unsigned]: [overflow](https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow) in the rust reference: integer operators panic on overflow in a debug build. for c, [n1570](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) 6.2.5 paragraph 9: unsigned arithmetic never overflows, it wraps around modulo one more than the largest value.

[^java]: [ArrayDeque](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayDeque.html) in the java 21 docs, and its [source](https://github.com/openjdk/jdk/blob/jdk-21-ga/src/java.base/share/classes/java/util/ArrayDeque.java) 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.

[^cpython]: [`_collectionsmodule.c`](https://github.com/python/cpython/blob/v3.15.0/Modules/_collectionsmodule.c#L71-L98) 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.

[^rust]: [VecDeque](https://doc.rust-lang.org/std/collections/struct.VecDeque.html) in the rust docs, and its [source](https://github.com/rust-lang/rust/blob/1.99.1/library/alloc/src/collections/vec_deque/mod.rs) 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.

[^go]: go's [standard library](https://pkg.go.dev/std@go1.27.2) at go1.27.2, with [container/list](https://pkg.go.dev/container/list@go1.27.2) and [container/ring](https://pkg.go.dev/container/ring@go1.27.2). neither the package list nor the [exported api](https://github.com/golang/go/tree/go1.27.2/api) has a deque.

[^chan]: [runtime/chan.go](https://github.com/golang/go/blob/go1.27.2/src/runtime/chan.go#L34-L46) 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.

[^swift]: [Deque.swift](https://github.com/apple/swift-collections/blob/1.7.3/Sources/DequeModule/Deque/Deque.swift#L50-L55) in swift-collections 1.7.3: the deque keeps its items in a circular buffer, so its storage may not be contiguous.

[^kmsg]: [printk basics](https://github.com/torvalds/linux/blob/v7.2/Documentation/core-api/printk-basics.rst) and [/dev/kmsg](https://github.com/torvalds/linux/blob/v7.2/Documentation/ABI/testing/dev-kmsg) in the linux docs at v7.2: the kernel log buffer is a ring buffer, and messages in it get overwritten.

[^algs4]: [ResizingArrayQueue.java](https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java.html) 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.

## related

- https://learning.anthnydas.com/ds/dynamic-array.md
- https://learning.anthnydas.com/ds/linked-list.md
- https://learning.anthnydas.com/algos/bfs.md
- https://learning.anthnydas.com/algos/dfs.md
- https://learning.anthnydas.com/ds/heap.md
