Heap / Priority Queue

A heap keeps its smallest item on top, and a push or pop only repairs one path from the top to a leaf, so each costs O(log n).

Kth largest: keep the k largest in a min-heap

StopHeap
numsk
nums
  1. 30
  2. 21
  3. 12
  4. 53
  5. 64
  6. 45
heapmin-heap · smallest on top

empty

size0

1/18The heap starts empty. It will keep the 2 largest numbers seen so far.

  • CH1 heap
Typical cost O(log n) per push/pop; O(n log k) for top-kFull lesson: Kth Largest Element in an Array →

When to reach for it

  • You need the k largest or smallest, not everything sorted.
  • You keep taking the smallest or earliest item while new ones arrive.
  • You need an answer after every item of a stream, like a running median.
  • Sorting everything works, but costs O(n log n) when k is small.

What stays true

A push adds at the end and swaps up past larger parents. A pop moves the last item into the root's place and settles it along one path. Either way, only one path from the root to a leaf changes.

Every parent is at most its children

StopHeap
InvariantEvery parent is at most its children, so the root is the smallest.✓ Holds
nums
  1. 50
  2. 11
  3. 42
  4. 23
  5. 84
  6. 35
  7. 76
heapmin-heap · smallest on top

empty

k4size0

1/19The heap starts empty. It will keep the 4 largest numbers seen so far.

  • CH1 heap

Break it

Each input here has tripped up a version of this code. The stage runs the one that gets it right.

Equal numbers count separately: the 4th largest is 4. Skipping repeats would give 3.

Kth largest on the inputs that trip it up

StopHeap
nums
  1. 30
  2. 21
  3. 32
  4. 13
  5. 24
  6. 45
  7. 56
  8. 57
  9. 68
heapmin-heap · smallest on top

empty

k4size0

1/25The heap starts empty. It will keep the 4 largest numbers seen so far.

  • CH1 heap
Answer4Steps25

Variants

Top k frequent elements

16/16
StopHeap
nums
  1. 40
  2. 11
  3. -12
  4. 23
  5. -14
  6. 25
  7. 36
count
  • 4×1
  • 1×1
  • -1×2
  • 2×2
  • 3×1
heapmin-heap

heap, slot by slot: 2 (-1), 2 (2)

k2seen5 of 5
  • CH1 heap

Count first, then keep the k most frequent as (count, value) pairs.

Step through it →

Find median from data stream

14/14
StopHeap
stream
  1. 50
  2. 151
  3. 12
  4. 33
lowmax-heap

low, slot by slot: 3, 1

highmin-heap

high, slot by slot: 5, 15

median4
  • CH1 low
  • CH2 high

Two heaps hold the smaller and the larger half. The median sits at their tops.

Step through it →

Meeting rooms II

27/27
StopHeap
meetings, by start
[0, 30]
[5, 10]
[15, 20]
[18, 25]
[25, 35]
heapmin-heap

heap, slot by slot: 30, 35

in progress2rooms3
  • CH1 heap

Keep the end times of meetings in progress on a heap. The earliest end says whether a room is free.

Step through it →

The code

The same algorithm in plain Python. The lit line is the one the current frame came from.

Kth largest: keep the k largest in a min-heap

StopHeap
nums
  1. 30
  2. 21
  3. 12
  4. 53
  5. 64
  6. 45
heapmin-heap · smallest on top

empty

k2size0

1/18The heap starts empty. It will keep the 2 largest numbers seen so far.

  • CH1 heap
kth_largest.py
import heapqdef find_kth_largest(nums, k):    if k > len(nums):        return None    heap = []    for x in nums:        heapq.heappush(heap, x)        if len(heap) > k:            heapq.heappop(heap)    return heap[0]

Drill it