Skip to main content
Beginner ~10 min read

Queues

First-in, first-out: enqueue, dequeue, and fairness. Plus deques and the circular-buffer trick.

Prerequisites: Arrays: Traversal, Insertion & Deletion

A queue is "first in, first out" (FIFO): enqueue adds at the back, dequeue removes from the front. Where the stack serves the most recent item, the queue serves in arrival order, it is the data structure of fairness. Task scheduling, print jobs, request handling, buffering, and breadth-first search all promise "things get processed in the order they arrived", and a queue is that promise kept.

Implementation detail that matters: an array used naively (shift() to dequeue) pays O(n) per operation because everything shifts left. Real queues either track head/tail indices into a ring buffer (wrap around the end, O(1) everything) or use a linked list with head AND tail pointers. JavaScript's clean answer for BFS-style usage is often two-index bookkeeping over one array, or pushing and index-walking. Know why the trick exists, shifting is the hidden O(n²) in many beginners' BFS.

Operation / caseCostNotes
enqueue (back)O(1)linked: tail pointer; ring: index bump
dequeue (front)O(1)linked: head pointer; ring: index bump
peek (front)O(1)—
Array with shift()O(n)shifts everything, avoid in hot paths

A ring buffer queue, all operations O(1)

queue-ring.js
class RingQueue {
  #buf;
  #head = 0;     // index of the front element
  #count = 0;    // how many elements are stored
  constructor(capacity = 8) { this.#buf = new Array(capacity); }

  enqueue(v) {
    if (this.#count === this.#buf.length) this.#grow();       // full → double
    const tail = (this.#head + this.#count) % this.#buf.length; // wrap around
    this.#buf[tail] = v;
    this.#count++;
  }

  dequeue() {
    if (this.#count === 0) return undefined;
    const v = this.#buf[this.#head];
    this.#head = (this.#head + 1) % this.#buf.length;           // wrap around
    this.#count--;
    return v;
  }

  #grow() {
    const bigger = new Array(this.#buf.length * 2);
    for (let i = 0; i < this.#count; i++) bigger[i] = this.#buf[(this.#head + i) % this.#buf.length];
    this.#buf = bigger;
    this.#head = 0;
  }
}

Check your understanding

  1. 1.enqueue(A), enqueue(B), dequeue(), enqueue(C), dequeue(). What was dequeued second?
  2. 2.Why is Array.shift() a trap for queue implementations?
  3. 3.Breadth-first search (Module 6) explores nodes level by level. Which structure produces that behavior?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Queue Operations

Play, pause, and scrub the real algorithm step by step.

Play it

Stack & Queue Puzzle

Hit exact pop and dequeue targets using LIFO and FIFO logic. Popping the wrong item teaches you the hard way w…

Keep going