Chapter 6 · Linear Structures

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 →

Person A (longest wait)
Person B
Person C
Person D (newest)
dequeue (front) ←→ enqueue (back)
🔍Stack vs. Queue in one sentence
A stack removes the item you just added (most recent). A queue removes the item added longest ago (oldest). Stack = LIFO. Queue = FIFO.
0 ops

Core operations: enqueue, dequeue, peek

0 ends

Items enter at one end and leave from the other

0 rule

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: 4
← FRONT (dequeue)BACK (enqueue) →
3[0]front
7[1]
1[2]
5[3]

Interactive 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

queue.pseudo
1Queue: two pointers (head, tail) into a dynamic array
2 
3enqueue(value): // add to back
4 array.append(value)
5 tail <- tail + 1
6 
7dequeue(): // remove from front
8 if isEmpty(): error
9 value <- array[head]
10 head <- head + 1 // O(1) with offset trick
11 return value
12 
13peek(): // read front without removing
14 if isEmpty(): error
15 return array[head]
16 
17isEmpty():
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&apos;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.

bfs.pseudo
1BFS(startNode):
2 queue <- new Queue
3 visited <- new Set
4 
5 enqueue(startNode)
6 visited.add(startNode)
7 
8 while queue is not empty:
9 current <- dequeue()
10 process(current)
11 
12 for each neighbour of current:
13 if neighbour not in visited:
14 enqueue(neighbour)
15 visited.add(neighbour)
16 
17// Queue ensures level-by-level traversal
18// Replace queue with stack -> DFS (depth-first)
💡One swap, totally different algorithm
The only difference between BFS and DFS is the data structure used. Swap the queue for a stack and you get depth-first search. This is why understanding queues and stacks is more important than memorizing specific algorithms.

Queues in the real world

Operating systems

CPU ready queue — processes waiting to run are managed in a queue. The scheduler dequeues the next process when CPU time is available.

Networking

Network packets are buffered in queues at routers. When a link is busy, packets wait in order rather than being dropped.

Print spoolers

Documents sent to a printer are queued. The first document submitted is always printed first, even if a smaller one arrives later.

Event loops

JavaScript&apos;s event loop uses a task queue. onClick, setTimeout callbacks wait in a FIFO queue until the call stack is empty.

Streaming / audio

Circular buffers (ring queues) decouple producer and consumer speeds, smoothing out rate mismatches without blocking either side.

Time complexity

Enqueue (add to back)O(1)

Constant time

Dequeue (remove from front)O(1)

Constant time

Peek (read front without removing)O(1)

Constant time

Search (queues are not designed for search)O(n)

Linear time

🎯 Quick Check

You enqueue: 1, 2, 3, 4. Then dequeue twice. Then enqueue 5. What is at the front of the queue?

🧠Queue vs Stack in interviews
If a problem says “process in order received” — use a queue. If it says “process the most recent first” or involves recursion — use a stack. When you see “shortest path” in an unweighted graph — BFS with a queue.

Queues: summary

Key points

  • push + shift on 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).