Chapter 8 of 13
Course Progress0 of 13 completed (0%)

Data Structures & Algorithms (DSA) Interview Mastery · Chapter 8 · ~15 min · Intermediate

Heaps, Priority Queues & Top-K Problems

Master logarithmic priority queues: translate complete binary trees into contiguous array indexing math, understand sift-up and sift-down heapify, and solve Top-K streaming problems in O(N log K) time.

  • Represent complete binary trees as flat contiguous arrays
  • Calculate parent (i-1)//2 and child 2i+1, 2i+2 indices
  • Understand sift-up and sift-down heapify operations in O(log N)
  • Solve Kth Largest Element using an O(N log K) streaming min-heap

Heaps, Priority Queues & Top-K Problems: learn it visually

Master logarithmic priority queues: translate complete binary trees into contiguous array indexing math, understand sift-up and sift-down heapify, and solve Top-K streaming problems in O(N log K) time.

Heaps, Priority Queues & Top-K ProblemsMaster logarithmic priority queues: translate complete binary trees into contiguous array indexing math, understand sift-up and sift-down heapify, and solve Top-K streaming problems in O(N log K) time.UNDERSTANDHeapsFOLLOW THE FLOWABCDPriority QueuesAPPLY ITTop-K ProblemsHeaps, Priority Queues & Top-K ProblemsMaster logarithmic priority queues: translate complete binary trees into contiguous array indexing math, understand sift-up and sift-down heapify, and solve Top-K streaming problems in O(N log K) time.UNDERSTANDHeapsFOLLOW THE FLOWABCDPriority QueuesAPPLY ITTop-K Problems

1Everyday Intuition: The Hospital ER Triage Room

In a hospital Emergency Room, patients do not receive medical care on a First-Come, First-Served basis (a simple queue).

If someone walks in with a mild headache at 2:00 PM, and an ambulance rushes in at 2:15 PM with a severe trauma patient, doctors attend to the trauma patient immediately.

This is a Priority Queue: items are extracted based on priority urgency rather than arrival time.

A Binary Heap is the high-performance data structure powering priority queues. It keeps the highest-priority item at the root in $O(1)$ access, and reorganizes in logarithmic $O(\log N)$ time whenever an item is added or removed.

Concept Check

Why is an array-based binary heap faster than a sorted array for implementing a priority queue?

2Architecture & Code Mechanics: Kth Largest Element in O(N log K)

Given an unsorted list of $N$ numbers, finding the $K$-th largest element by sorting the entire array takes $O(N \log N)$ time and requires storing the entire dataset in memory.

By maintaining a Min-Heap of size $K$, we only track the top $K$ largest candidates seen so far. The root min_heap[0] is the smallest of those $K$ elite numbers — exactly the $K$-th largest!

Wrong idea: Sorting the entire N-element dataset with sort() in O(N log N)

stream.sort(reverse=True); return stream[:5]O(N log N) time & O(N) memory · freezes on big data streams

If an incoming stream has 10,000,000 items and you only need the top 5 highest scores, sorting all 10M elements wastes gigabytes of RAM and billions of CPU cycles.

Real system: Maintaining a Min-Heap of size K in O(N log K) time & O(K) space

heapq.heappush(h, x); if len(h) > k: heapq.heappop(h)O(N log K) time & O(K) memory · handles infinite live streams!

Keep a heap capped at size K. When a new element arrives, push it and pop the smallest element if size > K. Memory stays pinned at K elements.

The Canonical Top-K Min-Heap Pattern:

import heapq

def find_kth_largest(nums: list[int], k: int) -> int:
    # Maintain a min-heap capped at size k
    min_heap = []

    for num in nums:
        heapq.heappush(min_heap, num)
        # If heap size exceeds k, evict the smallest candidate
        if len(min_heap) > k:
            heapq.heappop(min_heap)

    # The root is the smallest of the top k items (the K-th largest)
    return min_heap[0]
Concept Check

In Python's heapq array representation, if an element is at index i = 3, at which indices are its left and right children located?

3Interactive Visual Simulation: Min-Heap Array & Tree Sync

Click - Pop Min or + Push 5 below. Watch how the root element swaps with the leaf and sifts down to restore the min-heap invariant:

Live Min-Heap: Binary Tree & Contiguous Array Sync

Initial Min-Heap: Root is 3 (minimum). Every parent is smaller than both of its children.

Flat Array Representation: heap = [3, 7, 12, 18, 25, 14, 20]

3
[0]
7
[1]
12
[2]
18
[3]
25
[4]
14
[5]
20
[6]
3i=07i=112i=218i=325i=414i=520i=6
Concept Check

What is the time complexity of turning an arbitrary unsorted array of N elements into a valid heap using heapq.heapify()?

4Hands-On Challenge: Kth Largest Element Bug Hunt

In LeetCode #215 (Kth Largest Element in an Array), the starter code below contains two critical bugs: it pops when len(min_heap) >= k (keeping only $K-1$ elements) and returns the wrong index.

Fix the eviction boundary and return the root of the min-heap:

Heap Bug Hunt · kth_largest.py
Python

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Pop only when the heap exceeds $K$ items: if len(min_heap) > k: heapq.heappop(min_heap).
  • Return min_heap[0] (the root represents the $K$-th largest element).

5Architecture Recap & Next Steps

  • O(1) Peek & O(log N) Push/Pop: Min-heaps keep the minimum element at index 0 at all times.
  • Zero Pointer Overhead: Complete binary trees store cleanly in flat arrays using 2i + 1 and 2i + 2 child indexing.
  • Top-K Memory Bounding: A min-heap capped at size $K$ processes unbounded data streams in $O(N \log K)$ time and $O(K)$ space.
  • Max-Heap Trick: In Python, invert number signs (-val) to achieve max-heap behavior with heapq.

Congratulations on mastering DSA Foundations (Chapters 3-8)! Mark this chapter complete:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us