← Back to Algorithms, page 3

algorithms-0047 · Medium mid

Implement a binary min-heap with push, pop and peek, and build a heap from a list in O(n).

Store a complete binary tree in a list: the children of index i are 2i + 1 and 2i + 2, and the parent is (i - 1) // 2. push appends and sifts up; pop moves the last element to the root and sifts down; both are O(log n). Building a heap by sifting down from the last parent to the root is O(n), because most nodes are near the bottom and move only a little.

Full answer

Problem

Implement MinHeap with push(x), pop() (remove and return the smallest), peek(), len() and a constructor that builds a heap from a list.

Example: push 5, 3, 8, 1, 9, 2; popping six times returns 1, 2, 3, 5, 8, 9.

Constraints: up to 10^5 operations; pop and peek on an empty heap raise IndexError.

Brute force

A sorted list: peek and pop from the front are cheap if you keep it reversed, but each insert is O(n) because elements must shift. An unsorted list makes insert O(1) and pop O(n).

Optimal approach

Heap property: every parent is at most its children, so the minimum is at index 0.

  • push: append, then sift up: swap with the parent while smaller than it.
  • pop: save the root, move the last element to the root, then sift down: swap with the smaller child while larger than it.
  • Build: for i from n // 2 - 1 down to 0, sift down. Leaves already satisfy the property.

Why it works

A complete binary tree with n nodes has height about log2(n). Sift up and sift down each move one level per swap and fix the only place where the heap property can be broken, so push and pop are O(log n).

Bottom-up build is O(n): about n/2 nodes are leaves and never move, n/4 move at most one level, n/8 at most two, and so on. The sum n/4 x 1 + n/8 x 2 + n/16 x 3 + ... is less than n.

Complexity

push and pop: O(log n). peek: O(1). Build from a list: O(n). Space O(n).

Code

python
class MinHeap:
    """Binary min-heap in a list. push/pop O(log n), peek O(1), heapify O(n)."""

    def __init__(self, items=None):
        self.a = list(items or [])
        for i in range(len(self.a) // 2 - 1, -1, -1):   # bottom-up heapify
            self._sift_down(i)

    def push(self, x):
        self.a.append(x)
        self._sift_up(len(self.a) - 1)

    def pop(self):
        if not self.a:
            raise IndexError("pop from empty heap")
        top = self.a[0]
        last = self.a.pop()
        if self.a:
            self.a[0] = last
            self._sift_down(0)
        return top

    def peek(self):
        if not self.a:
            raise IndexError("peek from empty heap")
        return self.a[0]

    def _sift_up(self, i):
        while i > 0:
            parent = (i - 1) // 2
            if self.a[i] >= self.a[parent]:
                break
            self.a[i], self.a[parent] = self.a[parent], self.a[i]
            i = parent

    def _sift_down(self, i):
        n = len(self.a)
        while True:
            smallest, left, right = i, 2 * i + 1, 2 * i + 2
            if left < n and self.a[left] < self.a[smallest]:
                smallest = left
            if right < n and self.a[right] < self.a[smallest]:
                smallest = right
            if smallest == i:
                return
            self.a[i], self.a[smallest] = self.a[smallest], self.a[i]
            i = smallest

    def __len__(self):
        return len(self.a)


if __name__ == "__main__":
    h = MinHeap()
    for x in (5, 3, 8, 1, 9, 2):
        h.push(x)
    assert h.peek() == 1 and len(h) == 6
    assert [h.pop() for _ in range(6)] == [1, 2, 3, 5, 8, 9]
    for op in (h.pop, h.peek):
        try:
            op()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    h2 = MinHeap([7, 7, 2, 4, 0, 4])
    assert [h2.pop() for _ in range(len(h2))] == [0, 2, 4, 4, 7, 7]
    print("all tests passed")

Save as a47_min_heap.py and run python3 a47_min_heap.py. It prints all tests passed (Python 3.13.5).

Edge cases

Pop or peek on an empty heap raise IndexError. Popping the last element (do not copy it back to the root). Duplicates ([7, 7, 2, 4, 0, 4]). In Python, the heapq module provides these operations on plain lists; for a max-heap, push negated values or (-priority, item) tuples.

Pattern

Priority queue. Heaps power Dijkstra's shortest paths, task schedulers, k-way merge, top-k selection, running medians and event simulation.

python
class MinHeap:
    """Binary min-heap in a list. push/pop O(log n), peek O(1), heapify O(n)."""

    def __init__(self, items=None):
        self.a = list(items or [])
        for i in range(len(self.a) // 2 - 1, -1, -1):   # bottom-up heapify
            self._sift_down(i)

    def push(self, x):
        self.a.append(x)
        self._sift_up(len(self.a) - 1)

    def pop(self):
        if not self.a:
            raise IndexError("pop from empty heap")
        top = self.a[0]
        last = self.a.pop()
        if self.a:
            self.a[0] = last
            self._sift_down(0)
        return top

    def peek(self):
        if not self.a:
            raise IndexError("peek from empty heap")
        return self.a[0]

    def _sift_up(self, i):
        while i > 0:
            parent = (i - 1) // 2
            if self.a[i] >= self.a[parent]:
                break
            self.a[i], self.a[parent] = self.a[parent], self.a[i]
            i = parent

    def _sift_down(self, i):
        n = len(self.a)
        while True:
            smallest, left, right = i, 2 * i + 1, 2 * i + 2
            if left < n and self.a[left] < self.a[smallest]:
                smallest = left
            if right < n and self.a[right] < self.a[smallest]:
                smallest = right
            if smallest == i:
                return
            self.a[i], self.a[smallest] = self.a[smallest], self.a[i]
            i = smallest

    def __len__(self):
        return len(self.a)


if __name__ == "__main__":
    h = MinHeap()
    for x in (5, 3, 8, 1, 9, 2):
        h.push(x)
    assert h.peek() == 1 and len(h) == 6
    assert [h.pop() for _ in range(6)] == [1, 2, 3, 5, 8, 9]
    for op in (h.pop, h.peek):
        try:
            op()
            raise AssertionError("expected IndexError")
        except IndexError:
            pass
    h2 = MinHeap([7, 7, 2, 4, 0, 4])
    assert [h2.pop() for _ in range(len(h2))] == [0, 2, 4, 4, 7, 7]
    print("all tests passed")

List-based binary min-heap with sift up, sift down and bottom-up heapify; the test checks sorted pop order.

Complexity

Time: push and pop O(log n); peek O(1); build O(n). Space: O(n). Bottom-up heapify is O(n) because most nodes are near the leaves.

By level

Fresher: Implements push and pop with sift up and sift down, and explains the index formulas. Should be able to draw the list as a tree.

Mid: Builds the heap bottom-up, explains why it is O(n) and uses heapq idioms for max-heaps. Tests popping until the heap is empty.

Senior: Discusses decrease-key with a position map, d-ary heaps and cache effects, and when a balanced tree or indexed heap fits better. Can compare a binary heap with a balanced search tree for priority queues.

Key points

  • Children of i are 2i + 1 and 2i + 2
  • Parent of i is (i - 1) // 2
  • Push sifts up; pop sifts down
  • Bottom-up build is O(n), not O(n log n)
  • heapq is a min-heap; negate values for a max-heap

Common mistakes

  • Swapping with the larger child during sift down
  • Copying the last element back after popping the only element
  • Claiming heapify is O(n log n) without nuance
  • Using a heap when a sorted order of everything is needed

Follow-ups

  • How do you implement decrease-key?
  • How would you build a max-heap with heapq?
  • How does heapsort work and is it stable?

Tips

  • Draw the list as a tree
  • State the index formulas
  • Explain the O(n) build informally

Evaluation rubric

  • Correct sift operations
  • Correct index arithmetic
  • Correct complexity including build
  • Handles empty heap