kunal-kushwaha/DSA-Bootcamp-Java · error · Exception

Removing from empty Heap

Error message

Removing from empty Heap

What it means

Heap.remove() in the Huffman-coding lecture throws a checked Exception when the list backing the heap is empty, since extract-min needs a root node. In Huffman workflows it returns the next lowest-frequency node, so underflow breaks tree building.

Source

Thrown at lectures/27-huffman-coding/code/Heap.java:34

        return list.size();
    }
    private void upheap(int index){

        if(index == 0){
            return;
        }

        int p = parent(index);

        if(list.get(index).compareTo(list.get(p)) < 0){
            swap(index, p);
            upheap(p);
        }
    }

    public T remove() throws Exception{
        if(list.isEmpty()){
            throw new Exception("Removing from empty Heap");
        }
        T temp = list.get(0);

        T last = list.remove(list.size() - 1);

        if(!list.isEmpty()){
            list.set(0, last);

            downheap(0);
        }
        return temp;
    }

    private void downheap(int index) {

        int min = index;
        int left = left(index);
        int right = right(index);

View on GitHub (pinned to 6bc4d8bf8a)

Solutions

  1. Check isEmpty() (or size() >= 2 for the merge loop) before removing.
  2. Catch Exception around remove() and terminate tree building when empty.
  3. Handle the single-node/empty-input edge case before the merge loop.

Example fix

// before
Node left = heap.remove();
Node right = heap.remove();
// after
if (heap.size() >= 2) {
    Node left = heap.remove();
    Node right = heap.remove();
}
Defensive patterns

Strategy: validation

Validate before calling

if (heap.size() >= 2) {
    Node left = heap.remove();
    Node right = heap.remove();
}

Try / catch

try {
    Node left = heap.remove();
    Node right = heap.remove();
} catch (Exception e) {
    // fewer than two nodes left — finish tree building
}

Prevention

When it happens

Trigger: Calling remove() on an empty heap: extracting more nodes than inserted, calling remove() twice for merging when fewer than two nodes remain, or building a Huffman tree from an empty symbol set.

Common situations: Huffman tree construction loops calling remove() twice per merge but running one extra iteration; encoding with an empty frequency map; heaps built from empty input text so no nodes were ever added.

Related errors


AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31). Data as JSON: /api/errors/1437b2a570394172. Report an issue: GitHub.