krahets/hello-algo · error · IndexError

ヒープが空です

Error message

ヒープが空です

What it means

Raised by MyMaxHeap#pop (ja/codes/ruby/chapter_heap/my_heap.rb:83) when the heap is empty. pop swaps the root with the last leaf and removes it, which is invalid when @max_heap has no elements, so the guard blocks it. Message is Japanese: "Heap is empty".

Source

Thrown at ja/codes/ruby/chapter_heap/my_heap.rb:83

  ### ノード i から下から上へヒープ化 ###
  def sift_up(i)
    loop do
      # ノード i の親ノードを取得
      p = parent(i)
      # 「根ノードを越えた」または「ノードの修復が不要」になったらヒープ化を終了
      break if p < 0 || @max_heap[i] <= @max_heap[p]
      # 2 つのノードを交換
      swap(i, p)
      # ループで下から上へヒープ化
      i = p
    end
  end

  ### 要素をヒープから取り出す ###
  def pop
    # 空判定の処理
    raise IndexError, "ヒープが空です" if is_empty?
    # 根ノードと最も右の葉ノードを交換(先頭要素と末尾要素を交換)
    swap(0, size - 1)
    # ノードを削除
    val = @max_heap.pop
    # 上から下へヒープ化
    sift_down(0)
    # ヒープ先頭要素を返す
    val
  end

  ### ノード i から上から下へヒープ化 ###
  def sift_down(i)
    loop do
      # ノード i, l, r のうち値が最大のノードを ma とする
      l, r, ma = left(i), right(i), i
      ma = l if l < size && @max_heap[l] > @max_heap[ma]
      ma = r if r < size && @max_heap[r] > @max_heap[ma]

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check heap.is_empty? before pop.
  2. Bound extract loops by the original size captured before draining.
  3. Rescue IndexError around pop and treat empty as the normal completion of a drain.

Example fix

# before
while true
  heap.pop # raises once drained
end

# after
until heap.is_empty?
  heap.pop
end
Defensive patterns

Strategy: validation

Validate before calling

heap.pop unless heap.is_empty?

Type guard

def heap_nonempty?(h); h.respond_to?(:is_empty?) && !h.is_empty?; end

Try / catch

begin
  heap.pop
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling heap.pop when heap.is_empty? is true — before any push, or after extracting every element (e.g. heap-sort that drains the heap).

Common situations: Heap-sort / top-k routine that extracts one element too many; a priority-queue consumer that outran the producers; peeking/popping in a loop without an emptiness check.

Related errors


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