Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 12 of 20

Heaps (heapq)

A heap is a tree-shaped structure that always keeps the smallest (or, with a trick, the largest) item instantly available at the top. It is the engine behind a priority queue: "serve the most important thing next," not "serve whoever arrived first." Python's heapq module turns a plain list into a min-heap. Pushing or popping is O(log n); peeking at the smallest item (heap[0]) is O(1); building a heap from an existing list with heapq.heapify is O(n). Think of a hospital's emergency triage: the most critical patient is seen next, regardless of who walked in first - the opposite of the FIFO queue from the stacks-and-queues topic.

Operation Time
heapq.heappush / heappop O(log n)
peek at the smallest (heap[0]) O(1)
heapq.heapify (build from a list) O(n)

Flagship real-world example: trending posts, kept in a heap. Push each post's like count; once the heap holds more than k posts, pop the smallest - the post least likely to stay "trending":

import heapq

def top_k_trending(posts, k):
    heap = []
    for title, likes in posts:
        heapq.heappush(heap, (likes, title))
        if len(heap) > k:
            heapq.heappop(heap)             # drop the current lowest
    return sorted(((title, likes) for likes, title in heap), key=lambda p: -p[1])

posts = [("Monsoon trek photos", 420), ("New phone launch", 980),
         ("Diwali recipe thread", 1500), ("Startup funding news", 1100)]
print(top_k_trending(posts, 2))
# [('Diwali recipe thread', 1500), ('Startup funding news', 1100)]

This is O(n log k): the heap never holds more than k items, so it is far cheaper than sorting every post (O(n log n)) just to read off the top few. For a one-shot question, heapq has a shortcut:

print(heapq.nlargest(2, posts, key=lambda p: p[1]))
# [('Diwali recipe thread', 1500), ('Startup funding news', 1100)]

A priority queue for support tickets - most urgent first, regardless of arrival order:

tickets = []
for priority, ticket in [(2, "T-101"), (1, "T-102"), (3, "T-103")]:
    heapq.heappush(tickets, (priority, ticket))
while tickets:
    print(heapq.heappop(tickets))    # (1, 'T-102') first, then (2, 'T-101'), then (3, 'T-103')

⚠️ heapq gives a min-heap: the smallest item comes out first. The ticket example above already works as-is because lowest number = most urgent lines up with "smallest comes out first"; for a genuinely "biggest first" priority queue, either negate numeric priorities when pushing, or use heapq.nlargest/heapq.heapify with a key that flips the comparison.

Practice: k largest/smallest elements in a stream or list; top-k frequent items; merge several already-sorted lists cheaply with heapq.merge.

Read more: the official heapq documentation.

Practice on LeetCode - start here: Kth Largest Element in a Stream · Last Stone Weight · Kth Largest Element in an Array · Top K Frequent Elements · K Closest Points to Origin · Find Median from Data Stream (the last one is the full version of exercise 12 - save it for the end)

Show the full practice list (13 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Full program: examples/12_heaps.py.

Exercise 12: Heaps — running median of incoming prices

Scenario: A pricing dashboard needs the current median shown live as new prices stream in, without re-sorting the whole list every time. What to do: Write a class RunningMedian with an add(price) method and a median() method, using two heaps: a max-heap for the lower half (store negated values in a min-heap, since heapq only gives min-heaps) and a min-heap for the upper half, rebalanced after every add so their sizes never differ by more than one. Feed in the prices below one at a time and print the median after each.

Starting data:

PRICES = [100, 200, 50, 400, 300]

Sample output:

After 100: median 100
After 200: median 150.0
After 50: median 100
After 400: median 150.0
After 300: median 200
Show the solution to Exercise 12
"""Exercise 12: Heaps - running median of incoming prices.

Run:   python ex10.py   (macOS/Linux: python3 ex10.py)
"""

import heapq

PRICES = [100, 200, 50, 400, 300]


class RunningMedian:
    """Two heaps: `low` (max-heap, via negated values) holds the smaller
    half, `high` (min-heap) holds the bigger half. Kept within 1 of each
    other in size, so the median is always at the top of one or both.
    """

    def __init__(self) -> None:
        self.low: list[int] = []     # max-heap: store -value
        self.high: list[int] = []    # min-heap: store value

    def add(self, price: int) -> None:
        if not self.low or price <= -self.low[0]:
            heapq.heappush(self.low, -price)
        else:
            heapq.heappush(self.high, price)

        if len(self.low) > len(self.high) + 1:
            heapq.heappush(self.high, -heapq.heappop(self.low))
        elif len(self.high) > len(self.low) + 1:
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self) -> float:
        if len(self.low) > len(self.high):
            return -self.low[0]
        if len(self.high) > len(self.low):
            return self.high[0]
        return (-self.low[0] + self.high[0]) / 2


def main() -> None:
    tracker = RunningMedian()
    for price in PRICES:
        tracker.add(price)
        print(f"After {price}: median {tracker.median()}")


if __name__ == "__main__":
    main()

💡 Hint: After inserting into whichever heap is correct, if len(low) > len(high) + 1 move the top of low to high (or vice versa); the median is the top of the bigger heap, or the average of both tops when they are equal in size.

Search the guide