CMD Guide
HomeDSAHeap

Heap Operations

A binary heap keeps only one invariant — every parent obeys an order relation with its children — and enforces it locally after each mutation by bubbling the disturbed element up or down the tree, which is what lets insert and extract-root run in logarithmic time on an array with no pointers.

Recognize the pattern

Brute force vs. optimal

ApproachFind-min/maxInsertExtract-min/max
Unsorted array/listO(n) scanO(1) appendO(n) scan + remove
Sorted arrayO(1)O(n) shiftO(1) at the sorted end, O(n) elsewhere
Binary heapO(1) peekO(log n)O(log n)

The heap is the sweet spot: it never pays O(n) for insert or extract because it only restores order along a single root-to-leaf path, never the whole array.

Complexity, derived

Store the heap in an array; for index i, children are 2i+1, 2i+2 and parent is (i-1)/2. A complete binary tree of n nodes has height h = floor(log2 n).

Insert (heapify-up): append at index n (O(1) amortized for the array), then compare-and-swap with the parent at most once per level. Number of levels climbed ≤ h = O(log n), each step is O(1) work → total O(log n) time. Extra space: no recursion needed (iterative loop), so O(1) auxiliary space beyond the array itself.

Extract-root (heapify-down): move the last element to the root (O(1)), then at each level compare against up to 2 children and swap with the larger/smaller. Again bounded by height h → O(log n) time, O(1) auxiliary space.

Build-heap from n elements (not naive n inserts): calling heapify-down on all internal nodes bottom-up costs Σ (n / 2^(h+1)) · h summed over levels, which converges to O(n), not O(n log n) — because most nodes are near the bottom and sink only a short distance.

Traced example — inserting 2 into a Min-Heap

Heap array before insert: [3, 5, 4, 8, 9] (indices 0..4).

StepArray stateAction
0[3,5,4,8,9,2]Append 2 at index 5 (its parent is index (5-1)/2 = 2, value 4)
1[3,5,2,8,9,4]2 < 4 → swap indices 5 and 2; now at index 2, parent is (2-1)/2 = 0, value 3
2[2,5,3,8,9,4]2 < 3 → swap indices 2 and 0; now at index 0, the root — stop

Final heap: [2,5,3,8,9,4], valid Min-Heap in 2 swaps ≈ height (log2 6 ≈ 2.58).

Step through push and pop

The debugger below builds a min-heap by inserting values one at a time (each sifts up from the last slot), then does one extract-min (root leaves, the last element drops to the root and sifts down). Watch the array and the complete tree stay in lock-step; at each comparison, predict whether to swap or stop.

Java: array-backed min-heap core

class MinHeap {
    private int[] a;
    private int size = 0;

    MinHeap(int capacity) { a = new int[capacity]; }

    void insert(int val) {
        a[size] = val;
        int i = size++;
        while (i > 0 && a[(i - 1) / 2] > a[i]) {
            int parent = (i - 1) / 2;
            int tmp = a[i]; a[i] = a[parent]; a[parent] = tmp;
            i = parent;
        }
    }

    int extractMin() {
        int min = a[0];
        a[0] = a[--size];
        heapifyDown(0);
        return min;
    }

    // iterative on purpose: a recursive version costs O(log n) call stack,
    // which would contradict the O(1) auxiliary-space claim above
    private void heapifyDown(int i) {
        while (true) {
            int smallest = i, l = 2 * i + 1, r = 2 * i + 2;
            if (l < size && a[l] < a[smallest]) smallest = l;
            if (r < size && a[r] < a[smallest]) smallest = r;
            if (smallest == i) break;
            int tmp = a[i]; a[i] = a[smallest]; a[smallest] = tmp;
            i = smallest;
        }
    }
}

Standard Library PriorityQueue remove() Trap & Indexed Heaps

Standard libraries (like Java's java.util.PriorityQueue) store heaps as a flat array. They do not maintain a mapping from an element to its current index in the array. This creates a critical performance trap:

Pitfalls

When to use / when not

Use a heap when you need repeated access to a running min/max with online insertions (Dijkstra's frontier, top-k streaming, scheduling by priority). Avoid it when you need to search for an arbitrary element (O(n), no better than a list) or need full sorted order repeatedly (sort once, O(n log n), instead of extracting one-by-one for O(n log n) anyway but with more constant overhead and no random access).

StructureGet-minInsertArbitrary searchNotes
Binary heapO(1)O(log n)O(n)Best default priority queue
Balanced BST (TreeMap)O(log n)O(log n)O(log n)Use when you also need predecessor/successor or range queries
Sorted arrayO(1)O(n)O(log n)Use for static/rarely-mutated data

Takeaways

Recall: Why does building a heap from n elements bottom-up take O(n) time instead of O(n log n)?


Source: heap fundamentals as commonly taught in CLRS (Introduction to Algorithms) Ch. 6, cross-checked against the current page's insert/delete algorithm description.

🤖 Don't fully get this? Learn it with Claude

Stuck on Heap Operations? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Heap Operations** (DSA) and want to truly understand it. Explain Heap Operations from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Heap Operations** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Heap Operations** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Heap Operations** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes