krahets/hello-algo · error · Error

Queue is empty

Error message

Queue is empty

What it means

Thrown by LinkedListQueue.pop when front is null after peek. In practice this is a redundant/defensive guard: pop first calls peek(), which already throws 'Queue is empty' when size === 0, so this branch is effectively unreachable unless size and front fall out of sync. Treat it as the same empty-queue precondition as error 73.

Source

Thrown at en/codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts:49

    push(num: number): void {
        // Add num after the tail node
        const node = new ListNode(num);
        // If the queue is empty, make both front and rear point to the node
        if (!this.front) {
            this.front = node;
            this.rear = node;
            // If the queue is not empty, add the node after the tail node
        } else {
            this.rear!.next = node;
            this.rear = node;
        }
        this.queSize++;
    }

    /* Dequeue */
    pop(): number {
        const num = this.peek();
        if (!this.front) throw new Error('Queue is empty');
        // Delete head node
        this.front = this.front.next;
        this.queSize--;
        return num;
    }

    /* Return list for printing */
    peek(): number {
        if (this.size === 0) throw new Error('Queue is empty');
        return this.front!.val;
    }

    /* Convert linked list to Array and return */
    toArray(): number[] {
        let node = this.front;
        const res = new Array<number>(this.size);
        for (let i = 0; i < res.length; i++) {
            res[i] = node!.val;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check size() === 0 (or isEmpty if exposed) before pop.
  2. Drain with while (queue.size() > 0).
  3. Avoid mutating front/rear/queSize outside the class API.

Example fix

// before
const v = queue.pop(); // throws if empty

// after
const v = queue.size() === 0 ? undefined : queue.pop();
Defensive patterns

Strategy: validation

Validate before calling

const v = queue.size() === 0 ? undefined : queue.pop();

Type guard

function hasElements(q) { return typeof q.size === 'function' && q.size() > 0; }

Try / catch

try { return queue.pop(); }
catch (e) { if (!/Queue is empty/.test(e.message)) throw e; return undefined; }

Prevention

When it happens

Trigger: Popping an empty queue (normally surfaced via peek first); a corrupted state where queSize > 0 but front is null (should not happen in normal use).

Common situations: Calling pop without an emptiness check; consumer loops outrunning producers; internal pointer corruption from manual list mutation.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/32b148f0ee29a328. Report an issue: GitHub.