Heaps in Coding Interviews: The Essentials
Heaps are the data structure behind priority queues. They quietly solve a whole family of interview problems.
- What a heap is
A heap is a complete binary tree with one extra rule. In a min heap every parent is smaller than or equal to its children, so the smallest value always sits at the root. A max heap flips the rule so the largest value is on top.
- How it is stored
Because the tree is complete, it packs neatly into an array with no gaps.
For the node at index i, its children live at 2i + 1 and 2i + 2.
Its parent lives at (i - 1) // 2. No pointers are needed, which keeps heaps fast and memory friendly in practice.
Python ships a min heap in the heapq module.
It works on ordinary lists.
- Operations and their costs
Pushing and popping both take O(log n), because a value moves at most one level per step.
Reading the smallest element is O(1): it is always at index 0 of the list.
Turning an existing list into a heap with heapify is O(n).
Sorting would take O(n log n).
Python only has a min heap. For a max heap, push negated values and negate them again when you pop.
Searching for an arbitrary value is still O(n).
A heap only knows where the smallest element is.
- Patterns to recognize
Two patterns cover most heap questions: keeping the top k elements, and balancing two heaps to track a median.