Queue

A structure where the first item added is always the first one removed.

What is it?

Some work must be handled in arrival order: print jobs, support tickets, tasks waiting to run. A queue adds items at the back and removes them from the front, so whatever arrived first leaves first.

This rule is called FIFO: First In, First Out.

Explain like I'm 10

A queue is like a line at a coffee shop. New people join at the back, and whoever has waited longest is served next, from the front.

Examples

Using an array as a queue

const queue = [];

queue.push("first");  // ["first"]
queue.push("second");  // ["first", "second"]

console.log(queue.shift()); // "first" — removes and returns the front item
console.log(queue);         // ["second"]

push adds to the back and shift removes from the front, so together they act like a queue. Note: shift is O(n) on a plain array, since every remaining item shifts down.

How it works

A queue has two main operations: enqueue (add to the back) and dequeue (remove from the front). Ideally both are O(1).

In JavaScript, a plain array's .shift() is O(n) because everything shifts down. Real-world queues often use a linked list to keep both ends O(1).

enqueue("A")  enqueue("B")  dequeue()
     ↓             ↓            ↓
   [A]           [A,B]      returns "A", leaves [B]

Why does it exist?

Queues model anything handled in arrival order: task scheduling, message processing, serving requests, and breadth-first traversal of trees and graphs.

When to use it

Use a queue when things must be handled in the order they arrived: a task queue, a message queue, print jobs, or breadth-first traversal of a tree or graph.

When not to use it

If the newest item should go first, use a stack. For a high-throughput queue in real code, avoid a plain array's .shift(); use a linked-list-based queue or a dedicated library.

Common mistakes

  • Confusing a queue's FIFO order with a stack's LIFO order.

  • Using .shift() on a large array in performance-sensitive code without realizing it's O(n), not O(1).

  • Not checking whether a queue is empty before dequeuing.

Practice exercises

  1. Easy:

    Implement a Queue class with enqueue and dequeue methods.

  2. Medium:

    Use a queue to simulate a waiting line, printing the order people are served in.

  3. Hard:

    Use a queue to do a breadth-first traversal of a simple tree of nested objects.

Interview questions

What does FIFO mean?

First In, First Out: the earliest added item is always the first one removed.

What's a real-world use of a queue in software?

Task/job scheduling, request handling, and breadth-first search over trees and graphs.

Why is `.shift()` on a JavaScript array not ideal for a high-performance queue?

It's O(n): every remaining element moves down one index. A linked-list-based queue keeps both ends O(1).

What is a circular buffer (ring buffer), and how does it give a queue O(1) enqueue and dequeue using a fixed-size array?

It reuses a fixed-size array with a head index (where the next dequeue reads) and a tail index (where the next enqueue writes). Both wrap back to 0 with modulo at the end of the array. Nothing shifts; each operation reads or writes at an index and advances it, so both are O(1).

In a circular buffer, `head` and `tail` can both equal the same index whether the buffer is empty or completely full — how do implementations tell the two apart?

Most keep a separate count (or size) field, since head/tail alone is ambiguous. Others leave one slot always unused, so 'full' is (tail + 1) % capacity === head and 'empty' is head === tail.

Walk through enqueueing A, B, C and then dequeuing once, on an initially empty circular buffer of capacity 4. Where do `head` and `tail` end up?

Start: head=0, tail=0, count=0. enqueue(A): buffer[0]=A, tail becomes 1, count=1. enqueue(B): buffer[1]=B, tail becomes 2, count=2. enqueue(C): buffer[2]=C, tail becomes 3, count=3. dequeue(): returns buffer[head]=A, head becomes 1, count=2. Final state: head=1, tail=3, count=2, holding B and C.

Why must resizing a full circular buffer copy elements starting from `head`, rather than just copying the raw backing array index-by-index?

Once tail wraps past index 0, raw array order (0, 1, 2, ...) no longer matches insertion order, so a straight copy scrambles which item is oldest. Copying from head and wrapping exactly count times keeps the correct order in the new array.

What is a deque (double-ended queue), and how does it differ from a plain queue?

A deque supports O(1) insertion and removal at both ends. A plain queue is a deque limited to enqueue-at-back and dequeue-at-front.

What is a priority queue, and what does it typically use for insert/extract, along with the complexity of those operations?

It always returns the highest- (or lowest-) priority item next, whatever the arrival order. It's usually a binary heap: insert O(log n), extract-min/max O(log n), peek at the top O(1).

Why doesn't a plain unsorted list or a sorted array make a good priority queue?

An unsorted list needs an O(n) scan on every extraction. A sorted array extracts in O(1) but each insertion is O(n) to shift elements. A binary heap does both in O(log n), which is far better when both happen often.

Building a binary heap from n elements one at a time (n inserts) costs O(n log n) — but there's a way to build one from an existing array in O(n). What is it, and why is it faster?

Bottom-up heapify: from the last non-leaf node back to the root, sift each node down into place. Most nodes are near the bottom and need very few swaps, so the total work sums to O(n), not O(n log n) as with one-at-a-time inserts.

What is a monotonic queue (or deque), and what classic problem does it solve in O(n) instead of O(n·k)?

It solves sliding window maximum. The deque keeps indices whose values strictly decrease from front to back. Before pushing a new index, pop any smaller values from the back; they can never be the max while a larger, later value is in the window. The front is always the window's max. Each index is pushed and popped at most once, so the whole array takes O(n) instead of recomputing each window's max.

How does breadth-first search (BFS) use a queue, and what happens if you swap in a stack instead?

BFS enqueues newly discovered neighbors and dequeues from the front, so nodes are explored in discovery order, level by level. With a stack, the most recent node is explored next, giving depth-first order: a different traversal, not a slower BFS.

Why is a queue (not a stack) the structure behind a level-order tree traversal?

Level order visits every node at depth d before any at depth d+1. FIFO guarantees this: nodes come out in discovery order, so a whole level drains before the next level's nodes (enqueued after them) are reached.

What's the amortized time complexity of dequeue in a queue implemented with two stacks (`in` and `out`), and why can a single call still cost O(n)?

Amortized O(1). When out is empty, a dequeue moves every element from in to out: O(n) that time. But each element moves at most once in its lifetime, so n operations cost O(n) in total, O(1) on average.

Why does a linked-list-based queue need a reference to both the head and the tail node, when a stack built the same way only needs one?

A stack only touches the top, so one pointer is enough. A queue dequeues at the front and enqueues at the back. Without tail, enqueue walks the whole list to find the last node: O(n) instead of O(1).

What is a blocking queue, and where does it show up in concurrent programming?

A queue where dequeuing when empty (or enqueuing when a bounded queue is full) makes the thread wait instead of failing. It's the backbone of producer-consumer designs, like a thread pool's task queue, letting threads hand off work without busy-polling.

How does a JavaScript runtime's event loop use a queue?

Macrotask callbacks, like setTimeout callbacks or I/O completions, go on a task queue and run one at a time in the order queued (FIFO), interleaved with rendering and other work.

What's the time and space complexity of enqueue/dequeue on a well-implemented queue (linked list or circular buffer), versus using `.shift()` on a plain array?

O(1) time and O(1) extra space per operation for a linked-list queue (with head and tail pointers) and for a circular buffer (until it resizes). .shift() on a plain array is O(n) time, since every remaining element moves down one index.

Scenario: a task scheduler must process tasks in submission order, and thousands are submitted per second. Why would `array.push()` + `array.shift()` become a bottleneck, and what's the fix?

.shift() is O(n), so draining n tasks costs O(n²) in total, which dominates at high throughput. A circular buffer or linked-list queue keeps enqueue and dequeue O(1), so n tasks cost O(n).

What's a common off-by-one bug when implementing a circular buffer's wraparound?

Forgetting the modulo when advancing head/tail: writing tail = tail + 1 instead of tail = (tail + 1) % capacity. The index runs past the end of the array instead of wrapping to 0.

What happens if you call dequeue on an empty queue without checking first?

Depending on the implementation, it throws, returns undefined/null, or (in a hand-rolled circular buffer with no count check) reads stale data or corrupts the head/tail bookkeeping. Check for empty first.

Compare a circular-buffer-based queue to a linked-list-based queue in terms of memory layout and cache behavior.

A circular buffer is one contiguous pre-allocated array, so it's cache-friendly, but its capacity is fixed until an explicit O(n) resize. A linked-list queue grows one node at a time with no bulk resize, but nodes are usually separate heap allocations, causing more cache misses, plus an extra pointer per node.

Trace these operations on an initially empty queue: enqueue(1), enqueue(2), dequeue(), enqueue(3), dequeue(), dequeue(). What does each dequeue return, and what's left at the end?

enqueue(1) → [1]. enqueue(2) → [1,2]. dequeue() returns 1, leaving [2]. enqueue(3) → [2,3]. dequeue() returns 2, leaving [3]. dequeue() returns 3, leaving it empty. Items leave from the front in the order they were enqueued.

Why would you choose a priority queue over a regular queue for a hospital ER's 'next patient' system?

A regular queue serves in arrival order, but an ER must serve the most urgent patient first. A priority queue orders by urgency and extracts the top patient in O(log n) with a heap each time a slot opens.

What single difference between a stack and a queue — which end each operation happens at — changes the order items come out in?

A stack adds and removes at the same end: LIFO, newest out first. A queue adds at one end and removes at the other: FIFO, oldest out first. The same insertions come out in opposite orders.

What's the amortized time complexity of processing an entire n-element array through a monotonic queue (sliding window maximum), given that a single step can pop several elements at once?

O(n) amortized. One step can pop several smaller elements, but every element is pushed exactly once and popped at most once over the whole run, so total pushes and pops are O(n), not O(n) per step.

Why is a queue the right structure (not a stack) for a print spooler shared by many users?

Fairness: the first job submitted should print first, whoever sent it (FIFO). A stack prints the newest job first, so an early job could be starved forever by a stream of newer ones.

What's the difference between a bounded queue and an unbounded queue, and what does 'bounded' change about enqueue?

An unbounded queue grows as far as memory allows. A bounded queue has a fixed capacity, so enqueueing when full must reject the item, block until space frees up (a blocking queue), or evict something (like the oldest item).