krahets/hello-algo · error · Error

куча пуста

Error message

куча пуста

What it means

Thrown by MaxHeap.pop (JS, my_heap.js) with message 'куча пуста' ('heap is empty') when popping from an empty heap. pop swaps the root with the last leaf, removes the leaf, and sifts down — all meaningless on an empty structure, so the guard short-circuits.

Source

Thrown at ru/codes/javascript/chapter_heap/my_heap.js:85

    /* Начиная с узла i, выполнить просеивание снизу вверх */
    #siftUp(i) {
        while (true) {
            // Получение родительского узла для узла i
            const p = this.#parent(i);
            // Завершить heapify, когда «корневой узел уже пройден» или «узел не требует исправления»
            if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
            // Поменять два узла местами
            this.#swap(i, p);
            // Циклическое просеивание вверх
            i = p;
        }
    }

    /* Извлечение элемента из кучи */
    pop() {
        // Обработка пустого случая
        if (this.isEmpty()) throw new Error('куча пуста');
        // Поменять корневой узел с самым правым листом местами (поменять первый и последний элементы)
        this.#swap(0, this.size() - 1);
        // Удаление узла
        const val = this.#maxHeap.pop();
        // Просеивание сверху вниз
        this.#siftDown(0);
        // Вернуть элемент с вершины кучи
        return val;
    }

    /* Начиная с узла i, выполнить просеивание сверху вниз */
    #siftDown(i) {
        while (true) {
            // Определить узел с максимальным значением среди i, l и r и обозначить его как ma
            const l = this.#left(i),
                r = this.#right(i);
            let ma = i;
            if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check isEmpty() before popping: while (!heap.isEmpty()) { const v = heap.pop(); }
  2. Prefer peek() then pop() only when a value is expected.
  3. If draining into an array, bound the loop by heap.size() captured once.

Example fix

// before
while (true) { const v = heap.pop(); } // eventually throws

// after
while (!heap.isEmpty()) { const v = heap.pop(); process(v); }
Defensive patterns

Strategy: validation

Validate before calling

if (!heap.isEmpty()) { const v = heap.pop(); process(v); }

Try / catch

try {
  const v = heap.pop();
} catch (e) {
  if (e.message === 'куча пуста') { /* handle empty */ }
  else throw e;
}

Prevention

When it happens

Trigger: Calling pop() when #maxHeap.length === 0 (i.e., isEmpty() returns true). Common when draining a heap in a loop without checking size.

Common situations: Looping while(heap.size() >= 0) instead of > 0; popping more times than you pushed; using the heap as a priority queue that ran dry.

Related errors


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