A heap is a complete binary tree, stored in an array, where each parent is smaller than its children (min heap) or larger (max heap). The smallest or largest item is always at index 0, push and pop cost O(log n), and building a heap from a list with heapify costs O(n). It is the usual way to build a priority queue.
On this page
Min heap, max heap and the array layoutPython heapq: heapify, push, pop and priority queuesTop-k and merge k sorted listsHeap sortMistakes and practice orderFrequently asked questionsA heap answers one question quickly: what is the smallest (or largest) item right now? This page is for learners who know trees and want the heap properly: how the array layout works, what heapify does, how to use Python's heapq, and the two interview patterns that use it most, top-k and merging sorted lists.
All code ran on Python 3.9 on 1 December 2026. The heapq behaviour described follows the Python documentation. Google Trends India interest in the topic is seasonal; see the evidence note at the end.
Min heap, max heap and the array layout
A min heap keeps the smallest item at the top: every parent is less than or equal to its children. A max heap is the mirror image. Siblings have no order between them, so a heap is only partly sorted, which is why it is cheaper than keeping a full sorted list. A heap is also a complete binary tree: every level is full except possibly the last, which fills from the left. That shape lets you store it in a plain list with no pointers.
| For the item at index i | Formula (0-based) |
|---|---|
| Parent | (i - 1) // 2 |
| Left child | 2 * i + 1 |
| Right child | 2 * i + 2 |
| Root (min in a min heap) | index 0 |
The code stores a valid min heap, checks the formulas, then pushes and pops by hand using the two repair moves: sift up after adding at the end, sift down after moving the last item to the root.
heap = [2, 5, 3, 9, 6, 4] # a valid min-heap stored as a list
def parent(i): return (i - 1) // 2
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
i = 4
print("index", i, "value", heap[i], "-> parent", heap[parent(i)])
print("index 1 children:", heap[left(1)], heap[right(1)])
def push(h, x):
h.append(x)
i = len(h) - 1
while i > 0 and h[parent(i)] > h[i]: # sift up
h[parent(i)], h[i] = h[i], h[parent(i)]
i = parent(i)
def pop(h):
top, last = h[0], h.pop()
if h:
h[0] = last
i = 0
while True: # sift down
small = i
for c in (left(i), right(i)):
if c < len(h) and h[c] < h[small]:
small = c
if small == i:
break
h[i], h[small] = h[small], h[i]
i = small
return top
push(heap, 1)
print("after push(1):", heap)
print("pop:", pop(heap), "->", heap)Output:
index 4 value 6 -> parent 5
index 1 children: 9 6
after push(1): [1, 5, 2, 9, 6, 4, 3]
pop: 1 -> [2, 5, 3, 9, 6, 4]Pushing 1 added it at the end, then it moved up past 3 and 2 to the root. Popping returned 1 and the heap went back to the list we started with. Each repair walks at most the height of the tree, which is why push and pop are O(log n).
Python heapq: heapify, push, pop and priority queues
Python's heapq module implements a min heap on a plain list. There is no max heap class, so the usual trick is to push negated values. For a priority queue, push tuples: Python compares the first element, then the next on a tie. Add a counter as the second element so tied tasks keep their insertion order and never fall through to comparing task objects that may not be comparable.
import heapq
data = [9, 4, 7, 1, 8, 2]
heapq.heapify(data) # O(n), in place
print("heapified:", data)
heapq.heappush(data, 0)
print("pop smallest:", heapq.heappop(data))
# max-heap: push negatives
mx = []
for x in [3, 10, 6]:
heapq.heappush(mx, -x)
print("largest:", -heapq.heappop(mx))
# priority queue with tuples (priority, task); the counter breaks ties
tasks = []
for n, (pri, name) in enumerate([(2, "email"), (1, "fix bug"), (3, "lunch"), (1, "deploy")]):
heapq.heappush(tasks, (pri, n, name))
while tasks:
pri, _, name = heapq.heappop(tasks)
print(pri, name)Output:
heapified: [1, 4, 2, 9, 8, 7]
pop smallest: 0
largest: 10
1 fix bug
1 deploy
2 email
3 lunchNote that the heapified list is not sorted: only index 0 is guaranteed. Do not read a heap by iterating over the list and expect order; pop to get order. Interviewers like asking why heapify is O(n) and not O(n log n): most nodes sit near the bottom of the tree and move only a level or two. See time complexity and Big O for reading these costs.
| Operation | heapq call | Cost |
|---|---|---|
| Build from a list | heapq.heapify(a) | O(n) |
| Add an item | heapq.heappush(h, x) | O(log n) |
| Remove and return the smallest | heapq.heappop(h) | O(log n) |
| Peek at the smallest | h[0] | O(1) |
| Pop then push in one step | heapq.heapreplace(h, x) | O(log n) |
| k largest or smallest | heapq.nlargest(k, a), nsmallest | O(n log k) |
Top-k and merge k sorted lists
Top-k problems say: from a lot of items, give me the k biggest. Sorting everything costs O(n log n). A better plan is a min heap of size k: its root is the smallest of the k best so far, so a new item only matters if it beats the root. The same code works on a stream where you cannot hold all the data.
import heapq
scores = [42, 91, 17, 88, 65, 73, 99, 5]
print("top 3:", heapq.nlargest(3, scores))
print("bottom 2:", heapq.nsmallest(2, scores))
def top_k(stream, k):
heap = [] # min-heap of size k: its root is the k-th largest
for x in stream:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
print("streamed top 3:", top_k(iter(scores), 3))
words = ["a", "bb", "cc", "dddd", "e"]
print("longest 2:", heapq.nlargest(2, words, key=len))Output:
top 3: [99, 91, 88]
bottom 2: [5, 17]
streamed top 3: [99, 91, 88]
longest 2: ['dddd', 'bb']The speed gain is real for small k. On Python 3.9 on one laptop, with 300,000 random floats, getting the top 10 took about 43 ms by sorting and about 5 ms with heapq.nlargest. Your numbers will differ, so run it yourself:
import heapq, random, time
random.seed(1)
data = [random.random() for _ in range(300_000)]
t = time.perf_counter()
for _ in range(3): sorted(data)[-10:]
full = (time.perf_counter() - t) / 3
t = time.perf_counter()
for _ in range(3): heapq.nlargest(10, data)
heap = (time.perf_counter() - t) / 3
print("sorted(data)[-10:] ", round(full * 1000), "ms")
print("heapq.nlargest(10) ", round(heap * 1000), "ms")
print("same answer:", sorted(data)[-10:][::-1] == heapq.nlargest(10, data))Output on that run:
sorted(data)[-10:] 43 ms
heapq.nlargest(10) 5 ms
same answer: TrueMerge k sorted lists
To merge k sorted lists, keep a heap holding the current front item of each list. Pop the smallest, then push the next item from the same list. The heap never holds more than k items, so the total cost is O(N log k) for N items overall. heapq.merge does this for you and returns an iterator, and the hand-written version is what the interview question expects.
import heapq
a = [1, 4, 9]
b = [2, 3, 10]
c = [0, 5, 6, 11]
print("heapq.merge:", list(heapq.merge(a, b, c)))
def merge_k(lists):
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
out = []
while heap:
val, i, j = heapq.heappop(heap) # smallest head among all lists
out.append(val)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return out
print("by hand :", merge_k([a, b, c]))Output:
heapq.merge: [0, 1, 2, 3, 4, 5, 6, 9, 10, 11]
by hand : [0, 1, 2, 3, 4, 5, 6, 9, 10, 11]The same idea powers Dijkstra's shortest path, where the heap holds the next closest node (see Dijkstra's algorithm and graph data structure).
Heap sort
Heap sort has two steps: turn the array into a max heap (heapify, O(n)), then repeatedly swap the root, the largest item, with the last unsorted item and sift down on the shrinking heap. It sorts in place in O(n log n) in every case, but it is usually slower in practice than quicksort or Python's built-in sorted, and it is not stable. That trade is covered in sorting algorithms explained.
def sift_down(a, i, n): # max-heap version
while True:
big, l, r = i, 2 * i + 1, 2 * i + 2
if l < n and a[l] > a[big]: big = l
if r < n and a[r] > a[big]: big = r
if big == i:
return
a[i], a[big] = a[big], a[i]
i = big
def heap_sort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1): # build a max-heap bottom-up (heapify)
sift_down(a, i, n)
for end in range(n - 1, 0, -1): # move the max to the end, shrink the heap
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
return a
print(heap_sort([12, 3, 19, 7, 1, 15, 8]))Output: [1, 3, 7, 8, 12, 15, 19]
| Heap use | Why a heap fits | Example |
|---|---|---|
| Priority queue | Always serve the highest priority next | Task scheduler, hospital triage queue |
| Top-k | Keep only k candidates | Top 10 scores, trending items |
| Merge k sorted streams | Heap holds each stream's head | Merging log files, external sort |
| Running median | One max heap plus one min heap | Streaming statistics |
| Shortest path | Pick the nearest unvisited node | Dijkstra, routing |
Mistakes and practice order
- Expecting a sorted list. Only index 0 is the extreme; the rest is partly ordered.
- Using
heapqas a max heap directly. It is a min heap: push negative values, or negative priorities. - Comparing items that cannot be compared. If priorities tie and the next tuple element is a custom object, Python raises
TypeError; add a counter. - Using
list.sort()between pushes. Not needed and it wastes time; callheappushinstead. - Calling
min(list)in a loop. That is O(n) per call; a heap makes it O(log n) to update and O(1) to peek.
Practice in order: Kth Largest Element in an Array, Top K Frequent Elements, Last Stone Weight, K Closest Points to Origin, Merge k Sorted Lists, Find Median from Data Stream. More sources are on coding practice websites, and heap questions appear in the wider list at DSA interview questions. If you want a project that uses a priority queue, see Python projects for beginners. Parent path: DSA learning path.
Frequently asked questions
What is a heap in data structure?
A heap is a complete binary tree stored in an array in which each parent is ordered relative to its children: smaller in a min heap, larger in a max heap. That puts the minimum or maximum at index 0, giving O(1) peek and O(log n) insert and remove.
What is the difference between a min heap and a max heap?
In a min heap every parent is smaller than or equal to its children, so the smallest item is at the root. In a max heap every parent is larger than or equal to its children, so the largest item is at the root. Python's heapq is a min heap.
Is a heap the same as a priority queue?
No. A priority queue is an abstract idea: remove the highest-priority item first. A heap is a data structure that implements it efficiently. You can also build a priority queue with a sorted list, but inserts then cost O(n) instead of O(log n).
What does heapify do and what is its time complexity?
Heapify rearranges a list so that it satisfies the heap rule, by sifting items down starting from the last parent. It runs in O(n), not O(n log n), because most nodes are near the bottom and move only a few levels.
How do you make a max heap in Python?
The heapq module only provides a min heap, so store negated values: push -x and negate again when you pop. For tuples, negate the priority field. Alternatively wrap items in a class that reverses the comparison.
When should I use a heap instead of sorting?
Use a heap when you only need the smallest or largest k items, or when items keep arriving and you repeatedly need the current extreme. Use sorting when you need the whole list in order once. For k much smaller than n, a heap of size k is faster.
What is the difference between a heap and a binary search tree?
A BST orders all keys left to right, so it supports search and sorted traversal but costs pointers. A heap only orders parent against child, so it finds the extreme quickly but cannot search for an arbitrary key efficiently. See the BST page for the other side.
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


