A heap (also called a priority queue) is a structure that always knows its top item, the smallest or the largest, and lets you add items and remove the top quickly.
- A min-heap keeps the smallest item on top.
- A max-heap keeps the largest item on top.
What it's good at
| Operation | Unsorted array | Sorted array | Heap |
|---|---|---|---|
| Look at the smallest | O(n) | O(1) | O(1) |
| Add an item | O(1) | O(n) | O(log n) |
| Remove the smallest | O(n) | O(1) or O(n) | O(log n) |
A heap is the best of both: it doesn't keep everything sorted, only enough order to always know the top.
How it works inside
A heap is a binary tree stored in a plain array, filled level by level, left to right. For the item at index i:
- its children are at
2i + 1and2i + 2; - its parent is at
Math.floor((i - 1) / 2).
The one rule (for a min-heap): every parent is <= its children. So the smallest item is always at index 0.
The array [1, 3, 2, 7, 4] is this tree. Note it's not sorted: only each parent is smaller than its children.
- push: add the item at the end, then bubble it up: while it's smaller than its parent, swap them.
- pop: take the top, move the last item to the top, then sink it down: while a child is smaller, swap with the smaller child.
Each moves along one path of the tree, which is log n levels tall: O(log n).
Heaps in your language
Python has a built-in min-heap in heapq, working on a regular list:
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 1)
smallest = h[0] # look at the top: 1
smallest = heapq.heappop(h) # remove itFor a max-heap, store numbers negated (-x), and negate them back when you read them.
JavaScript/TypeScript have no built-in heap. In interviews you either write a small one (about 30 lines, see Find Median from Data Stream) or say "assume a priority queue class" and ask the interviewer if that's OK.
Patterns that use a heap
- "The k smallest / k largest": keep a heap of size
k. For theklargest, use a min-heap and pop whenever it grows pastk: the top is then thek-th largest. - "Repeatedly take the smallest": merging sorted lists (Merge K Sorted Lists), scheduling, Dijkstra's shortest path.
- "The middle of a stream": two heaps, one for each half (Find Median from Data Stream).
How to recognize this category
The problem keeps asking for the smallest/largest (or "next best") item while items are added or removed over time. If you only need it once, sorting is fine. If you need it again and again as things change, use a heap.
Common mistakes
- Expecting the heap's array to be sorted. Only the top is guaranteed.
- Using a min-heap when you need a max-heap (or forgetting to negate in Python).
- Sorting the whole array after every insert instead of using a heap: O(n log n) per step instead of O(log n).
- Python tuples with ties:
heapqcompares tuples item by item. If two entries tie on the first value and the second is an object that can't be compared, it crashes. Add a unique number (like an index) as a tie-breaker.