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.
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
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; }
} class MyCircularQueue:
def __init__(self, k):
self.a, self.head, self.size = [0] * k, 0, 0 # a[head] is the front
def enQueue(self, value):
if self.isFull():
return False
self.a[(self.head + self.size) % len(self.a)] = value # after the rear, wrapping
self.size += 1
return True
def deQueue(self):
if self.isEmpty():
return False
self.head = (self.head + 1) % len(self.a)
self.size -= 1
return True
def Front(self):
return -1 if self.isEmpty() else self.a[self.head]
def Rear(self):
return -1 if self.isEmpty() else self.a[(self.head + self.size - 1) % len(self.a)]
def isEmpty(self):
return self.size == 0
def isFull(self):
return self.size == len(self.a) class MyCircularQueue {
vector<int> a;
int head = 0, size = 0; // a[head] is the front
public:
MyCircularQueue(int k) : a(k) {}
bool enQueue(int value) {
if (isFull()) return false;
a[(head + size) % a.size()] = value; // the slot after the rear, wrapping around
size++;
return true;
}
bool deQueue() {
if (isEmpty()) return false;
head = (head + 1) % a.size();
size--;
return true;
}
int Front() { return isEmpty() ? -1 : a[head]; }
int Rear() { return isEmpty() ? -1 : a[(head + size - 1) % a.size()]; }
bool isEmpty() { return size == 0; }
bool isFull() { return size == (int)a.size(); }
}; class MyCircularQueue {
constructor(k) { this.a = new Array(k); this.head = 0; this.size = 0; } // a[head] is the front
enQueue(value) {
if (this.isFull()) return false;
this.a[(this.head + this.size) % this.a.length] = value; // after the rear, wrapping
this.size++;
return true;
}
deQueue() {
if (this.isEmpty()) return false;
this.head = (this.head + 1) % this.a.length;
this.size--;
return true;
}
Front() { return this.isEmpty() ? -1 : this.a[this.head]; }
Rear() { return this.isEmpty() ? -1 : this.a[(this.head + this.size - 1) % this.a.length]; }
isEmpty() { return this.size === 0; }
isFull() { return this.size === this.a.length; }
} The variations
-
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.Now you solve -
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.Now you solve -
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 - 1without 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.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.