Practice Discrete Math

Algorithms / Heap Invariants

Least You Need to Know: Heaps, Heap Invariants, and Fast Extremes

A heap stores items so the **root is always the minimum or maximum** according to a priority rule. It does not fully sort everything, but it lets you update the frontier quickly when you repeatedly need the next best element.

The least you need to know

Key notation

min-heap smallest key at the root
max-heap largest key at the root
sift up / sift down restore heap property after insert or remove

Tiny worked example

  • Put incoming tasks into a min-heap keyed by priority.
  • The root is always the next task with the smallest key.
  • After removing the root, move the last element to the top and sift down.
  • Only one path changes, so the repair is logarithmic rather than linear.

Common mistakes

How to recognize this kind of problem

Start practice