A heap is a binary tree that always keeps its smallest value at the top — or, in a max-heap, its largest. Reading that top value takes O(1). Adding a value or removing the top takes O(log n), however many values the heap holds.
That makes a heap the standard way to build a priority queue: a line where the most important item is served next, not the one that arrived first. Hospitals triage that way, operating systems schedule that way, and so do maps apps finding the shortest route.
Walk up from any node and, in a min-heap, every step leads to a smaller or equal value. So the root is the smallest value in the whole tree — without the heap ever comparing it with the far-away nodes.
A heap is not sorted. Along any path from the root down, values never decrease — but nothing is promised across branches. Siblings can be in either order, and a value on the bottom level can be smaller than one higher up on another branch.
Keeping only this much order is exactly what makes a heap cheap. A sorted array also keeps its smallest value at one end, but inserting into it shifts up to n values. A heap only ever repairs one path — about log₂ n nodes.
Because the tree is complete, it has no gaps — so a heap is stored as a plain array, level by level, left to right. There are no node objects and no pointers: positions do the linking. For the node at index i:
2i + 1,2i + 2,⌊(i − 1) / 2⌋ (rounded down).So moving between a parent and its children is just arithmetic: O(1), with no extra memory. Every heap operation in this course is built on these three formulas.
Put the two rules together. The shape rule holds automatically — an array has no gaps — so only the order rule needs checking: no parent may be bigger than either child. Only the first ⌊n / 2⌋ indexes have children, so the loop stops there.
Each step compares one parent with its children. One smaller child is enough to fail.
Time O(n), space O(1). For a max-heap, flip both comparisons: no child may be bigger than its parent.
The next lesson shows how push and pop keep both rules intact in O(log n).
A priority queue is the idea: items come out in priority order instead of arrival order. A heap is how it's almost always built. That's why the libraries use both names: Python's module is heapq, Java's class is PriorityQueue, and C++'s is priority_queue.
i are at 2i + 1 and 2i + 2, its parent at ⌊(i − 1) / 2⌋.Was this helpful?