CS concepts
Heaps Explained: 5 Top K Problems in Python
Updated Dec 1, 2026 · 4 min read
A min-heap keeps its smallest item on top, so you can read it in O(1) and push or pop in O(log n). For top K problems, keep a min-heap of size k: push every item and pop whenever the heap grows past k. What's left is the k largest, the top is the kth largest, and the whole run costs O(n log k) instead of O(n log n) for sorting.

Key points
- ●A heap is a list where every parent is smaller than its children; heap[0] is the minimum.
- ●Top K: a min-heap of size k keeps the k largest in O(n log k) time and O(k) space.
- ●For the k smallest, use a max-heap of size k; in Python, push negated values.
- ●Merge k sorted lists with a heap of the k list heads, and add an index to break ties.
- ●Running median: two heaps, a max-heap for the lower half and a min-heap for the upper half.

What a heap is
A heap is a tree with one rule: every parent is smaller than its children. That's a min-heap, and it means the smallest item always sits at the top, where you can read it in O(1).
You never build the tree. It's a plain list, and the children of position i live at 2i + 1 and 2i + 2. Python's heapq module does the work on that list. Push 5, 3, 8 and then 1, and the 1 lands at the bottom and swaps upward twice. The list becomes [1, 3, 8, 5]. That isn't sorted. A heap only promises the first item.
Push and pop are O(log n), because an item climbs or sinks one level at a time. A million items is only about 20 levels.
Kth Largest Element (LeetCode 215)
Given 3, 2, 1, 5, 6, 4, find the 2nd largest without sorting. Keep a min-heap of size k. Think of a club with k seats where the weakest member sits by the door. Each new number joins, and if the club is over k, the weakest leaves.
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
| Arrives | Leaves | Heap after |
|---|---|---|
| 3 | - | 3 |
| 2 | - | 2, 3 |
| 1 | 1 | 2, 3 |
| 5 | 2 | 3, 5 |
| 6 | 3 | 5, 6 |
| 4 | 4 | 5, 6 |
The top is 5, the 2nd largest. The heap never grows past k, so it's O(n log k) time and O(k) space. The Approach table on the visual sheet above sets this next to sorting at O(n log n).
Top K Frequent Elements (LeetCode 347)
For 1, 1, 1, 2, 2, 3 and k = 2, count first: 1 shows up 3 times, 2 twice, 3 once. Then run the same club with the count as the score. Push (count, value) pairs, since Python compares tuples by their first item.
count = Counter(nums)
heap = []
for num, c in count.items():
heapq.heappush(heap, (c, num))
if len(heap) > k:
heapq.heappop(heap)
return [num for c, num in heap]
The pair for value 3 gets popped, and the answer is 1 and 2. Counting is O(n) and the heap adds O(n log k). Bucketing values by count gets you O(n) if an interviewer pushes.
K Closest Points to Origin (LeetCode 973)
Points (3, 3), (5, -1) and (-2, 4), k = 2. Skip the square root: compare x squared plus y squared, which gives 18, 26 and 20. Now smaller wins, so the club flips and the farthest point sits by the door. Python only has a min-heap, so push the distance with a minus sign.
heap = []
for x, y in points:
heapq.heappush(heap, (-(x*x + y*y), x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]
When 20 arrives the heap is too big, and 26 leaves. The answer is (3, 3) and (-2, 4).
Merge k Sorted Lists (LeetCode 23)
Lists 1 4 5, 1 3 4 and 2 6. Each list is sorted, so the next output has to be one of the k heads. Keep only the heads in the heap, pop the smallest, attach it and push its next node.
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
heapq.heapify(heap)
dummy = tail = ListNode()
while heap:
val, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
The result is 1 1 2 3 4 4 5 6. The i in the tuple matters: two nodes with equal values would make Python compare the nodes, which raises a TypeError. Every node goes in and out once and the heap holds at most k, so it's O(n log k).
Find Median from Data Stream (LeetCode 295)
Numbers arrive one at a time, and after each you want the median. Use two heaps: lo, a max-heap (negated) for the smaller half, and hi, a min-heap for the larger half. The middle always sits at the tops.
def addNum(self, num):
heapq.heappush(self.lo, -num)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def findMedian(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2
For 5, 15, 1, 3 the medians are 5, 10, 5 and 4. After the last one, lo holds 1 and 3 and hi holds 5 and 15. Adding is O(log n) and reading the median is O(1).
The trap
heapq is a min-heap only. There's no flag for a max-heap, and code that expects the biggest on top quietly returns the smallest. Negate on the way in and flip the sign on the way out.
The second half of the trap is sorting out of habit. A heap of size k does O(n log k) work against O(n log n) for a sort, about 6 times less for a million numbers and k = 10. If one line is allowed, heapq.nlargest(k, nums) does the same job.
Frequently asked questions
Does Python have a max-heap?
heapq is a min-heap. The usual fix is to push negated values and flip the sign back when you pop. The newest Python versions add max-heap functions, but most interview judges run older versions, so negating is still the safe habit.
Why use a heap instead of sorting for top K?
Sorting costs O(n log n). A heap that never holds more than k items costs O(n log k). For a million numbers and k = 10 that's about 3.3 million steps instead of about 20 million, and the heap only ever holds 10 numbers.
Why does my heap crash with a TypeError on equal values?
When two tuples tie on their first item, Python compares the next item. If that's an object like a ListNode, it can't be compared and you get a TypeError. Put a unique index in the tuple before the object, as in (value, i, node).
Is a heap the same as a sorted list?
No. A heap only promises that the first item is the smallest. After pushing 5, 3, 8 and 1, Python's list is [1, 3, 8, 5]: the 1 is on top, but 8 comes before 5.