Design Data Structures · Pattern 4 of 10

Queues and ring buffers: fixed windows and streams

A queue serves items in arrival order. With a fixed capacity, an array plus a head index and a size wraps around with % k, so nothing ever shifts. Queues also keep "the last N items" or "the last 300 seconds" of a stream.

3 variations · 6 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A fixed capacity, or only the last k items matter
  • Events in time order, counted within a recent window
  • The oldest item leaves first
  • The first item that is still unique, still alive or still valid

The template

Queue / Circular Buffer
class MyCircularQueue {
    int[] a;
    int head = 0, size = 0;                  // a[head] is the front
    MyCircularQueue(int k) { a = new int[k]; }
    boolean enQueue(int value) {
        if (isFull()) return false;
        a[(head + size) % a.length] = value; // the slot after the rear, wrapping around
        size++;
        return true;
    }
    boolean deQueue() {
        if (isEmpty()) return false;
        head = (head + 1) % a.length;
        size--;
        return true;
    }
    int Front() { return isEmpty() ? -1 : a[head]; }
    int Rear() { return isEmpty() ? -1 : a[(head + size - 1) % a.length]; }
    boolean isEmpty() { return size == 0; }
    boolean isFull() { return size == a.length; }
}

The variations

  1. 1Ring buffer

    A fixed array, a head index and a size. The next free slot is (head + size) % k. A moving average is the same buffer plus a running sum: add the new value, subtract the one that falls out.

  2. 2A time window over a stream

    Timestamps arrive in order, so keep them in a queue and pop from the front while the oldest is outside the window. The queue length is the count. With many hits per second, store (time, count) pairs or use 300 buckets indexed by t % 300.

  3. 3Queue plus a lookup

    The queue keeps the order, a hash map or set answers questions about membership. The snake is a deque of cells plus a set for "is this cell my body". First unique keeps counts and pops repeated values from the front lazily, only when asked.

    Now you solve

Mistakes to avoid

  • Tracking head and tail without a size: an empty queue and a full queue then look the same.
  • Computing the rear as tail - 1 without wrapping: at index 0 it becomes −1.
  • Snake game: checking the collision with the tail before removing it. The tail moves away on the same step, so the head may enter that cell.
Next: Hash map + array: O(1) insert, delete and random →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.