A queue is a first-in, first-out collection. enqueue adds at the rear and dequeue removes from the front. A priority queue is a different abstraction: removal follows priority rather than arrival order.
If a and then b are enqueued and neither is removed, a must leave first. Track both front and rear so enqueue and dequeue remain constant time. Removing index zero from a dynamic array repeatedly is usually O(n) because remaining elements shift.
A fixed buffer can reuse released slots by wrapping indexes modulo capacity. Store the current size or reserve one slot to distinguish full from empty. Define whether the queue rejects, blocks, or grows when full.
A linked queue keeps head and tail pointers. Enqueue appends at tail; dequeue removes head; when the last value leaves, both pointers must return to empty. A deque supports insertion and removal at both ends and is useful for monotonic-window algorithms.
Queues support breadth-first search, task scheduling, message buffering, and producer-consumer boundaries. In production, an unbounded queue converts overload into memory growth and latency. Capacity, rejection, timeout, retry, and visibility are part of the queue contract.
class CircularQueue {
constructor(capacity) {
this.items = new Array(capacity);
this.front = 0;
this.size = 0;
}
enqueue(value) {
if (this.size === this.items.length) return false;
const rear = (this.front + this.size) % this.items.length;
this.items[rear] = value;
this.size++;
return true;
}
dequeue() {
if (this.size === 0) return undefined;
const value = this.items[this.front];
this.front = (this.front + 1) % this.items.length;
this.size--;
return value;
}
}
The queue processes vertices in discovery order and the visited set prevents repeated work.
function bfs(graph, start) {
const queue = [start], seen = new Set([start]), order = [];
for (let head = 0; head < queue.length; head++) {
const node = queue[head];
order.push(node);
for (const next of graph[node]) {
if (!seen.has(next)) { seen.add(next); queue.push(next); }
}
}
return order;
}
console.log(bfs({ A:['B','C'], B:['D'], C:[], D:[] }, 'A').join(' '));
A B C D
A FIFO queue removes the oldest item. A priority queue removes the item with the highest or lowest priority according to its ordering rule.
Practice, interview questions, and compiler links for Queue Data Structure.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.