BeginnerCoder

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).

Want it another way?
Task

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.

Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Data Structures

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.