krahets/hello-algo · error · RangeError
Heap is empty.
Error message
Heap is empty.
What it means
Thrown by MaxHeap.pop() (a RangeError 'Heap is empty.') when the heap contains no elements. pop() swaps the root with the last leaf, removes the last element, then sifts down from the root; calling it on an empty heap would swap/pop undefined indices, so the guard fails fast.
Source
Thrown at codes/typescript/chapter_heap/my_heap.ts:84
/* 从节点 i 开始,从底至顶堆化 */
private siftUp(i: number): void {
while (true) {
// 获取节点 i 的父节点
const p = this.parent(i);
// 当“越过根节点”或“节点无须修复”时,结束堆化
if (p < 0 || this.maxHeap[i] <= this.maxHeap[p]) break;
// 交换两节点
this.swap(i, p);
// 循环向上堆化
i = p;
}
}
/* 元素出堆 */
public pop(): number {
// 判空处理
if (this.isEmpty()) throw new RangeError('Heap is empty.');
// 交换根节点与最右叶节点(交换首元素与尾元素)
this.swap(0, this.size() - 1);
// 删除节点
const val = this.maxHeap.pop();
// 从顶至底堆化
this.siftDown(0);
// 返回堆顶元素
return val;
}
/* 从节点 i 开始,从顶至底堆化 */
private siftDown(i: number): void {
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
- Check size() or isEmpty() before popping: while (!heap.isEmpty()) { const v = heap.pop(); ... }.
- Track the count of pushes and never pop more than that.
- If the heap may be empty, guard each call rather than assuming upstream code left elements.
Example fix
// before
const top = heap.pop(); // throws when empty
// after
if (!heap.isEmpty()) {
const top = heap.pop();
} Defensive patterns
Strategy: validation
Validate before calling
function safePop(heap) {
return heap.isEmpty() ? undefined : heap.pop();
} Type guard
null
Try / catch
null
Prevention
- Always check heap.isEmpty()/size() before pop.
- Use while (!heap.isEmpty()) for drain loops.
- Track push count and never pop more than pushed.
When it happens
Trigger: Calling pop() when size() === 0 — e.g. draining the heap in a loop without a termination check, or popping after construction with no insertions.
Common situations: A while(true) pop loop with no isEmpty check; popping more times than you pushed; using the heap as a priority queue and dequeuing after the queue is drained.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/8eb21964957b5a83.
Report an issue: GitHub.