krahets/hello-algo · error · Error

The Deque Is Empty.

Error message

The Deque Is Empty.

What it means

Thrown by peekFirst() on an array-backed deque when the deque is empty. It guards the read nums[this.front] which would otherwise return undefined or stale data. peekFirst backs popFirst, so the same throw propagates from popFirst on an empty deque.

Source

Thrown at ru/codes/typescript/chapter_stack_and_queue/array_deque.ts:88

    /* Извлечение из головы очереди */
    popFirst(): number {
        const num: number = this.peekFirst();
        // Указатель головы сдвигается на одну позицию назад
        this.front = this.index(this.front + 1);
        this.queSize--;
        return num;
    }

    /* Извлечение из хвоста очереди */
    popLast(): number {
        const num: number = this.peekLast();
        this.queSize--;
        return num;
    }

    /* Доступ к элементу в начале очереди */
    peekFirst(): number {
        if (this.isEmpty()) throw new Error('The Deque Is Empty.');
        return this.nums[this.front];
    }

    /* Доступ к элементу в конце очереди */
    peekLast(): number {
        if (this.isEmpty()) throw new Error('The Deque Is Empty.');
        // Вычислить индекс хвостового элемента
        const last = this.index(this.front + this.queSize - 1);
        return this.nums[last];
    }

    /* Вернуть массив для вывода */
    toArray(): number[] {
        // Преобразовывать только элементы списка в пределах фактической длины
        const res: number[] = [];
        for (let i = 0, j = this.front; i < this.queSize; i++, j++) {
            res[i] = this.nums[this.index(j)];
        }

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check deque.isEmpty() before peekFirst()/popFirst().
  2. Bound consumption loops by the deque's current size.
  3. Wrap peekFirst in try/catch when an empty front is a legitimate control-flow signal.
  4. Log the size before access during debugging to catch over-consumption.

Example fix

// before
const head = deque.peekFirst(); // throws if empty

// after
const head = deque.isEmpty() ? null : deque.peekFirst();
Defensive patterns

Strategy: validation

Validate before calling

if (!deque.isEmpty()) {
    const head = deque.peekFirst();
}

Try / catch

try {
    const head = deque.peekFirst();
} catch (e) {
    if (e instanceof Error && e.message === 'The Deque Is Empty.') {
        // empty front; handle gracefully
    } else throw e;
}

Prevention

When it happens

Trigger: Calling peekFirst() or popFirst() on a freshly constructed deque; calling them after all elements have been popped; off-by-one in a loop that consumes one more element than present.

Common situations: Deque-based sliding-window or BFS code that does not bound its pop count by the deque size; mixing pushFirst/popLast counts asymmetrically until empty.

Related errors


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