Heap
A heap is a complete tree, usually stored in an array, where every parent obeys a priority relation with its children. In a min-heap the smallest value stays at the root; in a max-heap the largest does.
Start with this mental model
A heap is a complete tree, usually stored in an array, where every parent obeys a priority relation with its children. In a min-heap the smallest value stays at the root; in a max-heap the largest does.
How it works, without unnecessary jargon
A heap is not fully sorted. It only guarantees the parent/child heap property.
Insert and remove-root repair the heap by bubbling a value up or down.
Read the algorithm as a sequence of decisions
Append new value.
Bubble it upward while it violates the heap property.
For root removal, move the last value to root and bubble it down.
A min-heap used by Dijkstra always exposes the currently cheapest frontier node.
class MinHeap {
data = [];
push(value) {
this.data.push(value);
let i = this.data.length - 1;
while (i > 0) {
const p = Math.floor((i - 1) / 2);
if (this.data[p] <= this.data[i]) break;
[this.data[p], this.data[i]] = [this.data[i], this.data[p]];
i = p;
}
}
}Do not memorize the syntax. Follow the state that changes on each line and connect it to the invariant described above.
peek O(1), insert/remove O(log n)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Good fit
- Choose it when its dominant operations match your workload.
- Compare memory overhead as well as Big-O.
What usually goes wrong
- Memorizing complexity without understanding representation.
- Ignoring worst-case shape or resizing/rebalancing costs.
A professional answer shape
Do not say a heap is a sorted tree. Emphasize O(1) access to the best-priority item and O(log n) insertion/removal.
What problem does Heap solve?
A heap is a complete tree, usually stored in an array, where every parent obeys a priority relation with its children. In a min-heap the smallest value stays at the root; in a max-heap the largest does.
What should I mention about complexity?
Its typical cost here is peek O(1), insert/remove O(log n), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
What is the most common mistake?
Memorizing complexity without understanding representation.