krahets/hello-algo · error · Error

очередь пуста

Error message

очередь пуста

What it means

Thrown by peek() on an array-backed circular queue when isEmpty() is true. The message ('очередь пуста', Russian for 'queue is empty') guards the read nums[front]. Because pop() calls peek() first, the throw also propagates from pop() on an empty queue.

Source

Thrown at ru/codes/typescript/chapter_stack_and_queue/array_queue.ts:58

        // С помощью операции взятия по модулю вернуть rear к началу после выхода за конец массива
        const rear = (this.front + this.queSize) % this.capacity;
        // Добавить num в хвост очереди
        this.nums[rear] = num;
        this.queSize++;
    }

    /* Извлечь из очереди */
    pop(): number {
        const num = this.peek();
        // Указатель head сдвигается на одну позицию назад; если он выходит за конец, то возвращается в начало массива
        this.front = (this.front + 1) % this.capacity;
        this.queSize--;
        return num;
    }

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

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

/* Driver Code */
/* Инициализация очереди */
const capacity = 10;
const queue = new ArrayQueue(capacity);

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.isEmpty() before peek()/pop().
  2. Drive the consumer loop with while (!queue.isEmpty()).
  3. When capacity and size are confused, verify queSize rather than capacity before popping.
  4. Catch the error if an empty queue is an acceptable runtime condition.

Example fix

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

// after
while (!queue.isEmpty()) {
    const x = queue.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

if (!queue.isEmpty()) {
    const head = queue.peek();
}

Try / catch

try {
    const head = queue.peek();
} catch (e) {
    if (e instanceof Error && e.message === 'очередь пуста') {
        // queue empty; handle gracefully
    } else throw e;
}

Prevention

When it happens

Trigger: Calling peek() or pop() on a queue with queSize === 0; dequeuing in a loop that exceeds the number of enqueued elements; off-by-one in a producer/consumer where the consumer outruns the producer.

Common situations: BFS/level-order traversal that pops after the queue is drained; ring-buffer consumers that assume capacity implies available elements.

Related errors


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