What is a Heap?
Data Structures·7 min·Python code
Heaps are binary trees where every parent beats its children, so a min heap keeps the smallest value at the root and a max heap keeps the largest. Stored in an array, they power priority queues with O(log n) push and pop.
Heap Property and Priority Queues
Picture a hospital emergency room where patients are seen by urgency, not by arrival order. New patients keep coming, and you only need the most urgent case at every moment. Sorting the waiting room again after every arrival would waste time.
Priority queues solve this by keeping the smallest or largest value one step away while staying cheap to update.
Heaps look like binary trees with a loose rule. Parents are always more extreme than their children, smaller in a min heap and larger in a max heap. Siblings have no order, and nothing sorts left to right, which is weaker than the rule in a binary tree built for search.
That looseness is the point. After any change, the structure repairs itself by touching one path from the root down to a leaf.
Heap Array Index Math and Sift Operations
Levels fill from left to right with no gaps, so the shape removes the need for pointers. Plain arrays store the tree, with the root at index 0. For a node at index i, the children sit at 2i+1 and 2i+2 and the parent sits at (i-1)//2.
Two moves keep the heap property true. Push appends the new value at the end, then sifts up by swapping with its parent while the order is wrong. Pop removes index 0, moves the last value into its place, then sifts down by swapping with the smaller child (the larger child in a max heap) until the order is right.
Both moves follow one path, and a path is at most log n steps long. Push and pop cost O(log n), while peeking at the top costs O(1).
Heapify and Heap Sort
Building from an existing array costs O(n). Start at the last parent and sift down your way back to the root. Pushing n values one by one costs O(n log n), so sifting wins. Interviewers love asking about it.
Heap sort builds on it. Build a max heap, then keep popping the maximum and placing it at the end of the array. Sorting finishes in O(n log n) time with O(1) extra space, because the tree and the sorted part share one array.
Other sorting algorithms usually beat it in practice, yet it remains the textbook case for heaps.
Heap Code Example in Python
class MinHeap:
def __init__(self):
self.data = []
def push(self, x):
self.data.append(x)
i = len(self.data) - 1
while i > 0 and self.data[(i - 1) // 2] > self.data[i]:
p = (i - 1) // 2
self.data[i], self.data[p] = self.data[p], self.data[i]
i = p
def pop(self): # remove and return the minimum
top, last = self.data[0], self.data.pop()
if self.data:
self.data[0] = last
i, n = 0, len(self.data)
while True:
s, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and self.data[l] < self.data[s]: s = l
if r < n and self.data[r] < self.data[s]: s = r
if s == i: break
self.data[i], self.data[s] = self.data[s], self.data[i]
i = s
return top
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Heap Time and Space Complexity
| Time | O(log n) for push and pop, O(1) to peek at the top, O(n) to heapify and O(n log n) for heap sort |
|---|---|
| Space | O(n) for the backing array. Push and pop need O(1) extra space, and heap sort sorts in place |
Push and pop cost O(log n) in the average and worst case, and peeking is always O(1). Repeated sift down builds the array in O(n), which beats pushing values one at a time.
Watch Swaps Rearrange the Tree
Seeing every swap on your own numbers shows why push and pop touch only one path. Follow the swaps one step at a time.
When to Use a Heap
- You need the smallest or largest value again and again from a changing set. Task schedulers, event simulations and the frontier in Dijkstra and A* all do.
- Top k problems ask for the k largest, k smallest or k most frequent values. Keep k values in a priority queue and finish in O(n log k) instead of sorting everything.
- You merge k sorted lists or streams by always taking the next smallest head, like external merge sort does.
- You track a rolling median with two heaps, or anything else that needs the current extreme quickly when a full sort is overkill.
Mistakes to Avoid
- Treating a heap as sorted. Only the root is guaranteed to be extreme, so looping over the array does not give sorted order, and finding an arbitrary value takes O(n).
- Forgetting that Python's heapq module builds min heaps only. For a max heap, push negated values or tuples with a negated key, then negate again on the way out.
- Using the wrong heap for top k. Finding the k largest works well with a min heap of size k that evicts its smallest value. Heaping all n values costs more time and memory.
Heap FAQs
Is a heap the same as a binary search tree?
No. Both are binary trees, but a BST keeps full left to right order, which makes searching any value quick. Only the root is guaranteed to be the minimum or maximum, and siblings stay unordered. In return, push and pop stay cheap at O(log n).
What is the time complexity of heap operations?
Push and pop cost O(log n) because they follow one root to leaf path. Peeking at the top costs O(1). Heapify builds a heap from n values in O(n), and heap sort sorts in place.
When should I use a heap instead of sorting?
Reach for priority queues when values arrive over time or when you only need the extreme value or the top k. Sorting is a one time cost on fixed data. Priority queues handle every new value in O(log n) and solves top k in O(n log k), which wins when k is small.
Is a heap hard to learn?
Concepts here are friendly, because the single rule is that a parent beats its children. Array index math and the sift up and sift down logic need practice. Most learners feel comfortable after writing push and pop by hand once.
What is the difference between a min heap and a max heap?
Min heaps keep the smallest value at the root, and max heaps keep the largest. Parents are smaller than children in the first and larger in the second. Both use the same array layout and the same O(log n) moves.
How do I get a max heap in Python?
Python's heapq module only builds min heaps. Push the negative of every value, then negate again when you pop. For objects, push tuples that start with the negated key.
How do I practise heaps on CodeStory?
Watch push and pop in the visualiser, write the sift moves yourself, then try CodeStory's <a href="/practice/patterns/heap-priority-queue/">heap and priority queue practice problems</a>.
Related Guides
Guides are step one. In a CodeStory batch you code push and pop yourself, then explain every swap in a scored mock round.
Talk to a Mentor