Topic 10 of 14

Heap / Priority Queue Patterns

2 patterns and 10 practice problems, each with a recall tip, a diagram, the theory and a Python template.

01

Heap - Top K Elements

5 practice problems

Theory

  • To find the K largest: use a min-heap of size K. Push every element, pop when size > K.
  • To find the K smallest: use a max-heap (negate values in Python) of size K.
  • Alternative: quickselect for O(n) average but O(n²) worst case.
  • Heap of size K: O(n log K) total, better than sorting O(n log n) when K << n.

Code template

python
import heapq

def top_k_frequent(nums, k):
    freq = {}
    for n in nums:
        freq[n] = freq.get(n, 0) + 1
    # min-heap by frequency, pop smallest when size > k
    heap = []
    for num, count in freq.items():
        heapq.heappush(heap, (count, num))
        if len(heap) > k:
            heapq.heappop(heap)
    return [x[1] for x in heap]
02

Heap - Two Heaps (Median Tracking)

5 practice problems

Theory

  • Maintain a max-heap for the lower half and a min-heap for the upper half.
  • After each insertion, rebalance so sizes differ by at most 1.
  • Median is the top of the larger heap (or average of both tops if equal size).
  • Insert: O(log n). Get median: O(1).

Code template

python
import heapq

class MedianFinder:
    def __init__(self):
        self.lo = []  # max-heap (negate values)
        self.hi = []  # min-heap

    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

Practice problems · 5

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.