Queues
First In, First Out. The mirror image of a stack — here, the oldest item is always next. Queues model every real-world waiting line, and they are the backbone of breadth-first search, CPU scheduling, and network buffers.
What is a queue data structure?
A queue is a First In, First Out (FIFO) collection: items join at the back (enqueue) and leave from the front (dequeue), like a line at a shop. Queues schedule work in order: print jobs, task queues, message brokers and breadth-first search. In JavaScript, array.shift() is O(n), so use a linked list or an index pointer for large queues.
class Queue {
#items = {}; #head = 0; #tail = 0; // O(1) enqueue and dequeue
enqueue(x) { this.#items[this.#tail++] = x; }
dequeue() {
if (this.#head === this.#tail) return undefined;
const x = this.#items[this.#head]; delete this.#items[this.#head++]; return x;
}
get size() { return this.#tail - this.#head; }
}The physical model
A supermarket checkout line. People join at the back and leave from the front. Nobody cuts in. The person who has waited longest is always served first. That fairness guarantee is the entire value of a queue.
direction of travel →
Core operations: enqueue, dequeue, peek
Items enter at one end and leave from the other
First item in is always first item out
Live demo — try the operations
The highlighted item at the front is always next to leave. Enqueue adds to the back. Dequeue removes from the front.
Queue — First In, First Out (FIFO)
size: 4Interactive sandbox — code a Queue
Implement an optimized Queue that executes all dequeue events in constant O(1) time instead of shifting the array, and use it to simulate an operating system's CPU job scheduler live!
Code Editor
<button id="enq">enqueue</button> <button id="deq">dequeue</button>
<div id="queue"></div>
<p id="out"></p>Preview
Core operations
1Queue: two pointers (head, tail) into a dynamic array23enqueue(value): // add to back4 array.append(value)5 tail <- tail + 167dequeue(): // remove from front8 if isEmpty(): error9 value <- array[head]10 head <- head + 1 // O(1) with offset trick11 return value1213peek(): // read front without removing14 if isEmpty(): error15 return array[head]1617isEmpty():18 return head = tail
The naive dequeue problem
If you implement a queue with an array and shift all elements left on every dequeue, each dequeue costs O(n). With 1,000 items, that's 1,000 shifts per removal. There are two standard fixes:
Head offset trick
Instead of shifting, just move a "head" pointer one step to the right. Dequeue becomes O(1). Drawback: the array's left side fills with dead space. Solved by periodically compacting or using a circular buffer.
Circular buffer
Wrap the head and tail pointers around a fixed-size array using modulo arithmetic. head = (head + 1) % capacity. Zero wasted space, O(1) for all operations. Used in ring buffers for audio, network I/O, and OS scheduling.
Avoid: Naive shift (avoid this)
Move every element one index to the left after each dequeue. Simple to understand but O(n) per dequeue, making n dequeues cost O(n^2) total.
Queues power Breadth-First Search
BFS visits every node at distance 1 before any at distance 2, every node at distance 2 before any at distance 3, and so on. This level-by-level guarantee only works because of the FIFO property of queues.
1BFS(startNode):2 queue <- new Queue3 visited <- new Set45 enqueue(startNode)6 visited.add(startNode)78 while queue is not empty:9 current <- dequeue()10 process(current)1112 for each neighbour of current:13 if neighbour not in visited:14 enqueue(neighbour)15 visited.add(neighbour)1617// Queue ensures level-by-level traversal18// Replace queue with stack -> DFS (depth-first)
Queues in the real world
CPU ready queue — processes waiting to run are managed in a queue. The scheduler dequeues the next process when CPU time is available.
Network packets are buffered in queues at routers. When a link is busy, packets wait in order rather than being dropped.
Documents sent to a printer are queued. The first document submitted is always printed first, even if a smaller one arrives later.
JavaScript's event loop uses a task queue. onClick, setTimeout callbacks wait in a FIFO queue until the call stack is empty.
Circular buffers (ring queues) decouple producer and consumer speeds, smoothing out rate mismatches without blocking either side.
Time complexity
Constant time
Constant time
Constant time
Linear time
🎯 Quick Check
You enqueue: 1, 2, 3, 4. Then dequeue twice. Then enqueue 5. What is at the front of the queue?
Queues: summary
Key points
push+shifton an array works for small queues but is O(n) per dequeue.- Breadth-first search uses a queue to explore level by level.
- Variants: circular queue, deque (both ends) and priority queue (by priority, not arrival).
Frequently asked questions
›How do you implement a queue in JavaScript?
For small queues, an array with push and shift. For performance, an object or Map with head and tail counters (as above) or a linked list, which makes both operations O(1).