Lesson 25 — Ultimate: build a min-heap
Boss level: a heap from scratch
A min-heap is a binary tree stored in a plain list: the children of index i are at 2i + 1 and 2i + 2, and its parent is at (i − 1) // 2. The rule: every parent is ≤ its children, so the smallest item is always at index 0. Push: add at the end, then sift up — swap with the parent while the parent is bigger. Pop: take index 0, move the last item to the top, then sift down.
parent = (i - 1) // 2
Why it matters: this is exactly what heapq does inside; now you know why push and pop cost only O(log n).
Write the sift-up loop body in push(): swap h[i] with its parent, then move i to the parent.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Data Structures courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Data Structures books — check the publication year so the examples match current versions.
Search Amazon →