Array & Data-Structure Operations
Queue Enqueue and Dequeue
A queue is First-In-First-Out (FIFO): enqueue adds at the rear, dequeue removes from the front. This circular-array queue wraps the rear pointer around to reuse freed slots.
1Detailed explanation
A queue adds at the rear and removes from the front, so values leave in arrival order — FIFO.
Using a plain array and shifting elements on every dequeue would be O(n). A circular buffer avoids that: front and rear are indexes that advance with modulo arithmetic and wrap around to reuse freed slots, so both operations are O(1).
Queues schedule work (print queues, task queues), buffer streams and drive breadth-first search.
2Pseudocode
procedure enqueue(Q, value)
if Q.size = capacity
report overflow; return
Q.rear ← (Q.rear + 1) mod capacity
Q.data[Q.rear] ← value
Q.size ← Q.size + 1
procedure dequeue(Q)
if Q.size = 0
report underflow; return null
value ← Q.data[Q.front]
Q.front ← (Q.front + 1) mod capacity
Q.size ← Q.size − 1
return value3Interactive visualization
Size 0 / 4 · FIFO — values leave in the same order they arrived
A queue is First-In-First-Out (FIFO): enqueue adds at the rear, dequeue removes from the front. This circular-array queue wraps the rear pointer around to reuse freed slots.
4Implementations
Equivalent implementations in four languages — the same code the visualizer highlights line by line. Each is a complete program.
class Queue {
constructor(capacity) {
this.data = new Array(capacity).fill(null);
this.capacity = capacity;
this.front = 0;
this.rear = -1;
this.size = 0;
}
enqueue(value) {
if (this.size === this.capacity) {
console.log("Queue Overflow: cannot enqueue " + value);
return;
}
this.rear = (this.rear + 1) % this.capacity;
this.data[this.rear] = value;
this.size++;
}
dequeue() {
if (this.size === 0) {
console.log("Queue Underflow: nothing to dequeue");
return null;
}
const value = this.data[this.front];
this.data[this.front] = null;
this.front = (this.front + 1) % this.capacity;
this.size--;
return value;
}
toArray() {
const out = [];
for (let k = 0; k < this.size; k++) out.push(this.data[(this.front + k) % this.capacity]);
return out;
}
}
const queue = new Queue(4);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
console.log("Dequeued:", queue.dequeue());
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60);
console.log("Dequeued:", queue.dequeue());
console.log("Dequeued:", queue.dequeue());
console.log("Queue (front -> rear):", queue.toArray());
5Time and space complexity
Time: enqueue and dequeue only move the rear/front index with modulo arithmetic — no element is shifted — so both are O(1). (A plain array with shift() would make dequeue O(n).)
Space: The circular buffer has a fixed capacity n; each operation uses O(1) extra space.
6Common interview variations
- Design a circular queue (LeetCode 622).
- Implement a stack using queues.
- Sliding window maximum with a deque.
- Generate binary numbers 1..n with a queue.