Queues
A FIFO (First-In, First-Out) data structure. The first element added is the first one to be removed.
What is it?
A queue follows the "First-In, First-Out" (FIFO) principle, just like a line at a checkout counter. A great real-world tech example is a printer queue. When you and your colleagues send documents to a shared printer, each print job is added to the end of a queue (enqueued). The printer processes the jobs in the exact order they were received, taking the job from the front of the queue (dequeued). This ensures fairness and order. Web servers also use queues to handle incoming user requests. The first request to arrive is the first one to get a response, preventing newer requests from unfairly jumping ahead of older ones during high traffic.
Time Complexity
Implementation Example
const queue = [];
// Enqueue (add an element)
queue.push(10);
queue.push(20);
// Dequeue (remove the first element)
const firstElement = queue.shift(); // 10
console.log(firstElement);
// Peek (view the first element)
const peekElement = queue[0]; // 20
console.log(peekElement);Queues
Queues Deep Dive
Queues orchestrate work in the order it arrivesβperfect for event-driven systems, schedulers, and streaming pipelines.
?But why does this matter?
In production systems the choice between FIFO, priority, and circular queues determines latency characteristics more than raw throughput.
Visual Flow
How it actually moves
Enqueue
O(1)Insert at tail; circular buffers wrap indices instead of shifting.
Dequeue
O(1)Remove from head and advance pointer.
Peek
O(1)Inspect head without removal.
Breadth-first traversal
Initialize a queue with the starting node and mark it visited.
While the queue is not empty: dequeue the current node.
Process the node (e.g., record level order).
Enqueue any unvisited neighbors and mark them visited.
Watch the best explainer
Data structures: Introduction to Queues
mycodeschool
FIFO mechanics and circular-array implementation, step by step.
Picture boarding a plane
Passengers line up and are admitted in order. When the gate agent pauses boarding, the front of the line waits while the tail keeps forming.
Real-world analogy
Customer support chats funnel tickets into queues so agents serve the longest-waiting user first.
Takeaway
FIFO ordering keeps systems fair and predictable, especially when combined with back-pressure.
Practical applications
β’ Background job processors like Sidekiq or Celery.
β’ Print/job buffering in operating systems.
β’ Breadth-first search across social graphs or grid maps.
Technical insights
β’ Circular buffers avoid shifting data and keep enqueue/dequeue O(1).
β’ Multiple-producer multiple-consumer queues require careful memory barriers; use library implementations when possible.
β’ Priority queues add ordering guarantees at the cost of heap maintenance.
When to reach for it
β’ Task scheduling
β’ BFS traversal
β’ Streaming ingestion
Related topics
- stacks
- graphs
- searching
Operations Breakdown
Enqueue
O(1)Insert at tail; circular buffers wrap indices instead of shifting.
Dequeue
O(1)Remove from head and advance pointer.
Peek
O(1)Inspect head without removal.
Best practices
β’ Choose bounded queues for back-pressure; unbounded queues hide overload until memory spikes.
β’ Instrument queue length to detect latency regressions early.
β’ Use work-stealing queues when distributing tasks across CPU cores.
Common pitfalls
β’ False sharing occurs if head/tail counters live on same cache line under high contention.
β’ Priority queue misuse can starve lower-priority work.
β’ Failing to drain queues on shutdown leads to lost jobs.
Every kind of Queues
Interviewers rarely say which flavor they mean β they expect you to recognize it from the problem. Each variant below comes with the algorithms it unlocks.
Type 1 of 4
Simple FIFO Queue
β full pageFirst in, first out. The fairness structure: whoever waited longest is served next. BFS is "a queue applied to a graph".
What to know
- BFS explores in rings of increasing distance β the queue is what enforces that order.
- Implemented over a circular buffer or linked list for O(1) at both ends.
- Level-order tree traversal = BFS with a size snapshot per level.
Algorithms to reach for
BFS traversal
O(V + E)Shortest unweighted paths, level-order walks
Multi-source BFS
O(V + E)Spread from many starts at once (rotting oranges)
Recent counter / moving window
O(1) amortizedCount events inside a time window
In the wild: Print queues, message brokers (Kafka partitions, SQS), request queues, ticket lines.
Practice problems β hints, approach & solution on their own pages
Type 2 of 4
Deque (Double-Ended Queue)
β full pagePush and pop at both ends in O(1). The monotonic deque is the only known way to do sliding-window maximum in true O(n).
What to know
- Sliding window maximum: front holds the current maxβs index; smaller tails are evicted.
- Evict from the front when the index leaves the window.
- Also the natural structure for palindrome checking and work-stealing.
Algorithms to reach for
Monotonic deque window max
O(n)Max of every k-window in one pass (LeetCode 239)
0-1 BFS
O(V + E)Shortest paths with 0/1 edge weights β push-front for 0
Palindrome check
O(n)Compare characters popped from both ends
In the wild: Work-stealing thread pools, undo buffers, real-time min/max monitors on metrics streams.
Practice problems β hints, approach & solution on their own pages
Type 3 of 4
Circular / Bounded Queue
β full pageA fixed-capacity FIFO over a ring buffer. Memory never grows β old data is either rejected or overwritten by policy.
What to know
- Backpressure: a full queue signals producers to slow down.
- Single-producer single-consumer rings can be lock-free.
- Choice on overflow: block, drop-new, or overwrite-oldest.
Algorithms to reach for
Ring-buffer enqueue/dequeue
O(1)Constant-memory O(1) queue ops
Producer-consumer coordination
O(1) per itemDecouple fast producers from slow consumers
In the wild: Kernel network buffers, audio pipelines, IoT telemetry buffers, Disruptor pattern in trading.
Practice problems β hints, approach & solution on their own pages
Type 4 of 4
Priority Queue
β full pageNot FIFO at all: the highest-priority element leaves first, regardless of arrival. Almost always implemented as a binary heap.
What to know
- The queue interface hides a heap: insert and extract are O(log n).
- Dijkstra, Prim, A*, Huffman, and k-way merge are all priority-queue algorithms.
- See the Heaps deep dive for the mechanics of the underlying structure.
Algorithms to reach for
Dijkstra with PQ
O((V+E) log V)Always expand the closest unsettled node
K-way merge
O(N log k)Merge k sorted lists by popping the smallest head
Huffman coding
O(n log n)Merge two rarest symbols repeatedly
In the wild: OS process schedulers, hospital triage, event-driven simulators, job queues with priorities.
Practice problems β hints, approach & solution on their own pages
Pseudo Code β’ Breadth-first traversal
Flow Diagram
- Initialize a queue with the starting node and mark it visited.
- While the queue is not empty: dequeue the current node.
- Process the node (e.g., record level order).
- Enqueue any unvisited neighbors and mark them visited.
Hands-on code
Compare how the same idea looks in JavaScript, Python, and Go.
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
while (queue.length) {
const node = queue.shift();
order.push(node);
for (const neighbor of graph[node] ?? []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
return order;
}