Skip to content

Lesson 18 of 40Trees and graphs

Heaps

Use a heap to grab the smallest or largest item in O(log n), and solve top k, k-way merge and scheduling problems.

20 min read0/7 questions

A job scheduler always runs the most urgent task next. A game server matches the two closest-ranked players. A maps app expands the nearest unexplored road first. Each of these needs the same thing over and over: give me the smallest (or largest) item, fast, while new items keep arriving.

Sorting the whole list every time costs O(n log n) per request. A heap answers in O(log n), and it is the data structure behind priority queues in every language.

A tree that lives in an array

A min-heap is a binary tree with one rule: every parent is smaller than or equal to its children. So the smallest item is always the root. (A max-heap flips the rule, and the largest is at the root.)

Unlike a BST, a heap says nothing about left versus right. It only orders parents above children. That looser rule is what makes it cheap to maintain.

A heap is also a complete binary tree: every level is full except possibly the last, which fills from the left. Because there are no gaps, you can store it in a plain array, level by level, with no pointers at all. For the item at index i:

RelativeIndex
left child2 * i + 1
right child2 * i + 2
parent(i - 1) // 2

Here is the same min-heap two ways. Node 3 is at index 1, so its children are at indexes 3 and 4.

The array
1
0
3
1
2
2
7
3
5
4
4
5

Index 0 holds the root, the smallest value: 1.

1/3
The same heap as a tree
735142
Quick check
In a heap array, the item at index 9 has its parent at which index?
Need a nudge? A hint rules out a wrong answer.

Push: sift up

To add an item, put it at the end of the array (the next free spot in the bottom level). It may be smaller than its parent, which breaks the rule. So swap it upward until its parent is smaller. This is sift up.

To remove the smallest item, take the root. Move the last item into the root's place, then swap it down with its smaller child until both children are bigger. This is sift down.

Push 5, 3, 8, 1, then pop
5

Push 5 into an empty heap. It is the root.

1/7

A complete tree with n items has about log₂ n levels, and each sift moves one level per swap. So push and pop are O(log n), and peeking at the minimum is O(1) (it is just index 0).

Heapify: O(n), not O(n log n)

To turn an existing list into a heap, you could push items one by one: O(n log n). Heapify does better. Sift down every non-leaf node, starting from the last one and moving toward the root.

Why is that O(n)? Half the nodes are leaves and need no work. A quarter are one level up and sift at most one step. An eighth sift at most two steps. Most nodes are near the bottom, where sifting is cheap, and the total adds up to less than 2n swaps. Python's heapq.heapify does exactly this.

Heaps in Python and TypeScript

Python ships heapq: plain functions that treat a list as a min-heap. Before Python 3.14 there was no max-heap at all, so the standard trick is to negate values on the way in and out. (The 3.14 additions are covered further down.)

Python
import heapq nums = [5, 3, 8, 1, 9, 2]heapq.heapify(nums) # O(n), in placeprint(nums[0]) # peek at the minimum heapq.heappush(nums, 0)print(heapq.heappop(nums), heapq.heappop(nums)) # Max-heap: store negativesmax_heap = []for x in [5, 3, 8]: heapq.heappush(max_heap, -x)print(-heapq.heappop(max_heap)) # Tuples compare by first item, so (priority, task) workstasks = [(2, "write tests"), (1, "fix prod bug"), (3, "refactor")]heapq.heapify(tasks)print(heapq.heappop(tasks)[1])
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

import heapq
h = []
for x in [4, 1, 7, 3]:
  heapq.heappush(h, -x)
print(-heapq.heappop(h), -heapq.heappop(h))
Need a nudge? Hints walk you through it.

The top k pattern

"Find the k largest numbers" in a stream of a million. Sorting is O(n log n) and needs all the data at once. Instead, keep a min-heap of size k holding the k largest seen so far. Its root is the smallest of those k, the one most likely to be kicked out.

For each new number: push it, and if the heap grows past k, pop the smallest. At the end, the heap holds the k largest and the root is the k-th largest.

Python
import heapq def kth_largest(nums, k): heap = [] for x in nums: heapq.heappush(heap, x) if len(heap) > k: heapq.heappop(heap) # drop the smallest of the k + 1 return heap[0] print(kth_largest([3, 2, 1, 5, 6, 4], 2))print(kth_largest([7, 7, 1, 9], 3))
Output
Press Run (⌘ Enter) to see what happens.

Each step costs O(log k), so the whole thing is O(n log k) time and O(k) space. With k = 10 and n = 1,000,000, that is far cheaper than sorting, and it works on a stream you can only read once.

The counterintuitive part trips people up: for the k largest, you use a min-heap. For the k smallest (or k closest points), use a max-heap of size k.

Quick check
You want the 10 closest points to the origin out of 5 million. Which is the best plan?
Need a nudge? A hint rules out a wrong answer.

Two heaps: the running median

To report the median of a stream after every number, split the numbers into two halves. A max-heap holds the smaller half (its root is the largest of the small numbers) and a min-heap holds the larger half. Keep their sizes within one of each other. The median is the root of the bigger heap, or the average of both roots when they are the same size. Each new number costs O(log n). This is the median-finder practice problem.

K-way merge: one candidate per list

You have k sorted lists (log files from k servers, k sorted shards of a database query) and need one sorted stream. Comparing the heads of all k lists at every step costs O(k) per item. A heap holds one candidate per list, the smallest item that list has not output yet, so the next item overall is always the heap's root.

Pop the root, output it, and push the next item from the same list. The heap never holds more than k entries, so each item costs O(log k), and merging N items in total costs O(N log k). Each heap entry carries where it came from, (value, list_index, position), so you know which list to refill from.

Merging [1, 4, 7], [2, 5, 8] and [3, 6, 9]
213

Start with the head of each list. The root, 1, is the smallest item anywhere, because every list is sorted.

1/5
Python
import heapq def merge_sorted(lists): heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) out = [] while heap: value, i, j = heapq.heappop(heap) out.append(value) if j + 1 < len(lists[i]): # replace it with its successor heapq.heappush(heap, (lists[i][j + 1], i, j + 1)) return out def kth_smallest(matrix, k): """Rows and columns are sorted ascending.""" n = len(matrix) heap = [(matrix[r][0], r, 0) for r in range(min(n, k))] heapq.heapify(heap) for _ in range(k - 1): _, r, c = heapq.heappop(heap) if c + 1 < len(matrix[r]): heapq.heappush(heap, (matrix[r][c + 1], r, c + 1)) return heap[0][0] assert merge_sorted([[1, 4, 7], [2, 5], [], [0, 9]]) == [0, 1, 2, 4, 5, 7, 9]grid = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]assert kth_smallest(grid, 8) == 13assert [kth_smallest(grid, k) for k in range(1, 10)] == sorted(x for row in grid for x in row)print(merge_sorted([[1, 4, 7], [2, 5], [], [0, 9]]))print(kth_smallest(grid, 8))print(list(heapq.merge([1, 4, 7], [2, 5], [0, 9]))) # the built-in, lazy
Output
Press Run (⌘ Enter) to see what happens.

The index i in each tuple does two jobs: it says which list to refill from, and it breaks ties when two values are equal, so Python never has to compare the third items. For linked lists, the same idea is Merge k Sorted Lists, which Linked List Techniques covers along with the divide-and-conquer alternative.

Kth Smallest Element in a Sorted Matrix is a k-way merge in disguise: each row is a sorted list. Start with the first item of each row, pop k − 1 times, and the root is the answer. That is O(k log n) for an n × n matrix. The alternative interviewers like to hear is binary search on the answer value (see Binary Search): count the items <= mid with a staircase walk from a corner in O(n), giving O(n log(max − min)). The heap is simpler to get right; the binary search wins when k is close to n².

In Python, heapq.merge(*iterables) does a lazy k-way merge for you and is the right call at work, for example when merging sorted files too large to load at once (the merge step of an external sort).

Quick check
You merge k = 100 sorted lists holding N = 1,000,000 items in total with a heap of one candidate per list. What is the time?
Need a nudge? A hint rules out a wrong answer.

Task Scheduler: a heap plus a cooldown queue

You have CPU tasks labelled by letter, and the same letter must wait at least n time units before it runs again. Each unit you can run one task or sit idle. What is the minimum total time?

The greedy rule: at every time unit, run the available task with the most copies left. Running the most frequent task first keeps the idle gaps small, because it is the task that would otherwise pile up at the end with nothing to fill the gaps between its copies. So keep a max-heap of remaining counts for tasks that are ready, and a queue of tasks cooling down, each with the time it becomes ready again. The queue stays in time order on its own, because tasks enter it in the order they run.

Python
import heapqfrom collections import Counter, deque def least_interval(tasks, n): """Simulate: max-heap of remaining counts, queue of tasks cooling down.""" heap = [-c for c in Counter(tasks).values()] heapq.heapify(heap) cooling = deque() # (ready_time, -remaining) time = 0 while heap or cooling: time += 1 if heap: left = heapq.heappop(heap) + 1 # run one: count moves toward 0 if left: cooling.append((time + n, left)) if cooling and cooling[0][0] == time: heapq.heappush(heap, cooling.popleft()[1]) return time def least_interval_formula(tasks, n): counts = Counter(tasks).values() top = max(counts) ties = sum(1 for c in counts if c == top) return max(len(tasks), (top - 1) * (n + 1) + ties) assert least_interval(list("AAABBB"), 2) == 8 # A B idle A B idle A Bassert least_interval(list("AAABBB"), 0) == 6assert least_interval(list("AAAAAABCDEFG"), 2) == 16import randomfor _ in range(500): tasks = random.choices("ABCDE", k=random.randint(1, 15)) n = random.randint(0, 4) assert least_interval(tasks, n) == least_interval_formula(tasks, n)print(least_interval(list("AAABBB"), 2), least_interval_formula(list("AAABBBCCDE"), 2))
Output
Press Run (⌘ Enter) to see what happens.

The simulation is O(T log 26) for T time units, which is effectively linear. The formula is O(n) to count and worth knowing because interviewers often ask for it next. Lay out the most frequent task, with top copies, as top − 1 full frames of length n + 1, plus a last partial frame holding every task that ties for the top count. That is (top − 1) · (n + 1) + ties. If there are so many other tasks that the frames overflow, no idle time is needed at all and the answer is just len(tasks). Take the max of the two. The random test at the end checks the simulation and the formula against each other, which is exactly how you would gain confidence in a formula you derived under pressure.

Predict the outputPython

What does this print?

from collections import Counter
tasks, n = list("AAABBBCCDE"), 2
counts = Counter(tasks).values()
top = max(counts)
ties = sum(1 for c in counts if c == top)
print(max(len(tasks), (top - 1) * (n + 1) + ties))
Need a nudge? Hints walk you through it.

Tie-breakers: never let Python compare the payload

heapq compares tuples item by item. If two entries tie on priority, Python moves on to compare the second items. When those are dicts, objects or anything without <, you get a TypeError, usually only in production, on the first day two jobs share a priority.

Python
import heapqimport itertools jobs = []heapq.heappush(jobs, (1, {"name": "deploy"}))try: heapq.heappush(jobs, (1, {"name": "backup"})) # tie on priorityexcept TypeError as e: print("TypeError:", e) order = itertools.count()jobs = []for priority, name in [(2, "email"), (1, "deploy"), (1, "backup"), (2, "report")]: heapq.heappush(jobs, (priority, next(order), {"name": name}))print([heapq.heappop(jobs)[2]["name"] for _ in range(len(jobs))])
Output
Press Run (⌘ Enter) to see what happens.

The fix is a monotonic counter in the middle: (priority, count, item). Counts are unique, so the comparison never reaches the item. It has a second benefit: equal-priority entries come out in insertion order (first in, first out), which a heap does not guarantee by itself because heaps are not stable. Most job queues want that fairness. To break ties differently, put the rule in the tuple: (priority, -created_at, count, item) gives newest first among equals.

The other option is a small class with __lt__ (or @dataclass(order=True) with the payload marked field(compare=False)). That is cleaner when the ordering rule is complicated, but each comparison calls Python code, so tuples are faster in hot loops.

Lazy deletion: removing from the middle

A heap is fast at the root and slow everywhere else. Removing an arbitrary item means finding it (O(n)) and then repairing the heap. Problems like Sliding Window Median need exactly that: as the window moves, the outgoing number must leave one of the two heaps.

The standard trick is lazy deletion. Do not remove the item now. Record that it is pending removal, and drop it later, when it reaches the root and you would otherwise return it. Use a Counter, not a set, because the same value can be in the heap several times and only some copies may be deleted. Keep your own size too, since len(heap) now includes dead entries.

Python
import heapqfrom collections import Counter class RemovableMinHeap: """A min-heap that supports remove(x) by deleting lazily.""" def __init__(self): self.heap = [] self.pending = Counter() # value -> copies waiting to be dropped self.size = 0 def push(self, x): heapq.heappush(self.heap, x) self.size += 1 def remove(self, x): # O(1): caller promises x is present self.pending[x] += 1 self.size -= 1 def _clean(self): while self.heap and self.pending[self.heap[0]]: self.pending[heapq.heappop(self.heap)] -= 1 def peek(self): self._clean() return self.heap[0] def pop(self): self._clean() self.size -= 1 return heapq.heappop(self.heap) h = RemovableMinHeap()for x in [5, 1, 8, 1, 3]: h.push(x)h.remove(1)h.remove(3)assert h.size == 3assert h.pop() == 1 # one copy of 1 is still liveassert h.peek() == 5 # 3 was skipped on the wayassert h.size == 2print(h.pop(), h.pop(), h.size)
Output
Press Run (⌘ Enter) to see what happens.

Every pushed item is popped at most once, live or dead, so the cleanup is amortised O(log n) per operation. The cost is memory: dead entries sit in the heap until they surface. If deletions far outnumber pops, rebuild the heap from the live items now and then. You have met the same idea twice already in other lessons: Dijkstra skips stale entries whose distance is out of date (Shortest Paths), and Max Stack keeps a stack and a heap in sync with a removed set of ids (Design Problems). When items have unique ids, mark ids; when values repeat, count values, as here.

Quick check
A lazy-deletion heap stores pending removals in a set of values instead of a Counter. The heap holds 4, 4, 9 and you remove one 4. What goes wrong?
Need a nudge? A hint rules out a wrong answer.

Max-heaps in Python 3.14

For years the only way to get a max-heap from heapq was the negation trick above. Python 3.14 added public max-heap functions: heapify_max, heappush_max, heappop_max, heappushpop_max and heapreplace_max. They work on a plain list arranged with the largest item at index 0.

Python
import heapq if hasattr(heapq, "heappush_max"): # Python 3.14+ nums = [5, 3, 8, 1] heapq.heapify_max(nums) heapq.heappush_max(nums, 9) print(heapq.heappop_max(nums), nums[0]) h = []for x in [5, 3, 8, 1]: heapq.heappush(h, -x) # any version: negate in and outheapq.heappush(h, -9)print(-heapq.heappop(h), -h[0])
Output
Press Run (⌘ Enter) to see what happens.

Know both. Many interview platforms and company servers still run Python versions older than 3.14, and the negation trick works everywhere. It also has a limit: you can only negate numbers. For a max-heap of strings or tuples with mixed directions, either use the 3.14 functions or wrap items in a class whose __lt__ is reversed. In an interview, say which version you are assuming before you call heappush_max.

Match the pairs0/6 matched

Match the problem to the heap setup.

Choose an item, then its match on the other side.

Common mistakes:

  • Using a min-heap for "k smallest" (you need to evict the largest, so use a max-heap).
  • Forgetting that heapq is min-only and negating only on the way in, not on the way out.
  • Assuming the heap array is sorted. Only heap[0] is guaranteed; heap[1] is not the second smallest.
  • Pushing tuples whose second items cannot be compared (two equal priorities with dict payloads raise a TypeError). Add a counter as a tie-breaker: (priority, count, item).
ChallengeMedium

Kth Largest Element

Given a list of integers nums and a number k, return the kth largest value. This is the kth largest in sorted order, so duplicates count separately.

nums = [3, 2, 1, 5, 6, 4],          k = 2  →  5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4  →  4

Try to beat sorting the whole list.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
def find_kth_largest(nums: list[int], k: int) -> int: # Keep only the k largest values seen so far in a min-heap. pass
ChallengeMedium

K Closest Points to the Origin

Given a list of points points, where each point is [x, y], and a number k, return the k points closest to the origin (0, 0) by straight-line distance. You can return them in any order.

points = [[1, 3], [-2, 2]],          k = 1  →  [[-2, 2]]
points = [[3, 3], [5, -1], [-2, 4]], k = 2  →  [[3, 3], [-2, 4]]

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= x, y <= 10^4
  • The tests are chosen so the answer is unique.
def k_closest(points: list[list[int]], k: int) -> list[list[int]]: # Keep the k closest points so far in a max-heap keyed by distance. pass

Build the structure yourself once. It makes every heap question easier to reason about.

ChallengeMedium

Build a min-heap

Implement a min-heap of numbers stored in a plain array, without using heapq or any library heap.

Methods:

  • push(x) adds a value (sift it up).
  • pop() removes and returns the smallest value (move the last item to the root, then sift it down). Return None / undefined when the heap is empty.
  • peek() returns the smallest value without removing it (None / undefined when empty).
  • size() returns how many values are stored.
h = MinHeap()
h.push(5); h.push(2); h.push(8)
h.peek()  → 2
h.pop()   → 2
h.pop()   → 5
h.size()  → 1

For the item at index i, its children are at 2i + 1 and 2i + 2 and its parent is at (i - 1) // 2. push and pop must be O(log n).

class MinHeap: def __init__(self) -> None: self.data: list[int] = [] def push(self, x: int) -> None: pass def pop(self) -> int | None: pass def peek(self) -> int | None: pass def size(self) -> int: pass
Key terms
min-heap
A complete binary tree where every parent is less than or equal to its children, so the minimum is at the root.
sift up / sift down
Swap a new item up toward the root, or a moved root down toward the leaves, until the heap rule holds. O(log n).
heapify
Build a heap from a list in O(n) by sifting down every non-leaf from the bottom up.
heapq
Python's min-heap functions on a list. Negate values for a max-heap.
top k pattern
Keep a heap of size k and evict the root when it overflows. O(n log k) time, O(k) space.
k-way merge
Merge k sorted sequences by keeping one candidate per sequence in a heap. O(N log k) for N items.
tie-breaker
A unique counter in the heap tuple, (priority, count, item), so equal priorities never compare items and come out first in, first out.
lazy deletion
Record an item as removed and discard it when it reaches the root, instead of deleting it from the middle.
Interview pattern: Heap / Priority Queue30 problemsSpot it: Top k · k-th largest · merge sorted streams · scheduling