Skip to the content

Lesson 129 of 296

Queues

What you will learn

  • What a queue is (FIFO)
  • Why array.shift() makes a slow queue
  • Building a real O(1) queue
  • Deques
  • A queue built from two stacks
On this page

What is a queue?

A queue adds items at the back and removes them from the front. The first item added is the first removed: FIFO (First In, First Out). Like a queue at a shop.

OperationMeaning
enqueueAdd to the back
dequeueRemove from the front
peekLook at the front

Where queues appear: breadth-first search (Lessons 137 and 141), the event loop's task queue (Lesson 68), job queues on servers (Part 15), print queues.

The shift() trap

TypeScript
function queueWithShiftDemo(): number[] {
  const q: number[] = [];
  q.push(1);
  q.push(2);
  q.push(3);
  const first = q.shift()!;
  return [first, ...q];
}

push is O(1), but shift is O(n): every remaining item moves one place forward. A BFS over a million nodes using shift becomes O(n²). For small inputs it is fine, and interviewers often accept it if you mention the cost.

A real O(1) queue

Keep an array and a head index instead of removing from the front:

TypeScript
class Queue<T> {
  private items: T[] = [];
  private head = 0;

  enqueue(item: T): void {
    this.items.push(item);
  }

  dequeue(): T | undefined {
    if (this.head >= this.items.length) return undefined;
    const item = this.items[this.head];
    this.head++;
    if (this.head > 1024 && this.head * 2 > this.items.length) {
      this.items = this.items.slice(this.head);
      this.head = 0;
    }
    return item;
  }

  peek(): T | undefined {
    return this.items[this.head];
  }

  get size(): number {
    return this.items.length - this.head;
  }
}

The occasional slice removes used slots so memory does not grow forever. Because it happens rarely, dequeue is O(1) amortised (Lesson 116).

A linked list with head and tail pointers (Lesson 133) is another O(1) queue.

Deque

A deque (double-ended queue, said "deck") allows adding and removing at both ends in O(1). Used in sliding window maximum problems and some BFS variations. JavaScript has no built-in deque; you can build one with a circular buffer or a doubly linked list.

Queue from two stacks

Problem (LeetCode 232): implement a queue using only stack operations.

Idea: push onto an in stack. To dequeue, if the out stack is empty, pour everything from in into out, which reverses the order, so the oldest item is on top.

TypeScript
class QueueFromStacks<T> {
  private inStack: T[] = [];
  private outStack: T[] = [];

  push(item: T): void {
    this.inStack.push(item);
  }

  pop(): T | undefined {
    this.moveIfNeeded();
    return this.outStack.pop();
  }

  peek(): T | undefined {
    this.moveIfNeeded();
    return this.outStack.at(-1);
  }

  empty(): boolean {
    return this.inStack.length === 0 && this.outStack.length === 0;
  }

  private moveIfNeeded(): void {
    if (this.outStack.length === 0) {
      while (this.inStack.length > 0) this.outStack.push(this.inStack.pop()!);
    }
  }
}

Each item is moved at most once, so every operation is O(1) amortised.

Priority queue

A priority queue removes the item with the highest priority first (not the oldest). It is built with a heap (Lessons 139 and 140).

How to say it in an interview

"A queue is FIFO. In JavaScript, push plus shift works but shift is O(n), so for large inputs like BFS I use a head index into an array, compacting occasionally, which gives amortised O(1) dequeue, or a linked list. A deque supports both ends. A queue from two stacks pours the input stack into the output stack only when the output is empty, giving amortised O(1) operations."

Key words

WordMeaning
QueueA collection where items leave in the order they arrived
FIFOFirst in, first out
Enqueue / dequeueAdd to the back / remove from the front
DequeA double-ended queue
Priority queueRemoves the highest-priority item first

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.