DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Trees · Topic 9 of 18

Heap / Priority Queue

Always know the smallest (or largest) item in O(1), and add or remove one in O(log n).

Spot it

Signals in the question

⌕k-th largest / smallest, or the top k of something.

⌕Repeatedly take the current best (next meeting, closest point, cheapest edge).

⌕Merging many sorted lists or streams.

The idea

O(n log k) time · O(k) space

For the k-th largest, keep a min-heap of the k biggest numbers seen so far. When it grows past k, drop its smallest. At the end, the smallest of the k biggest is the answer.

Template · Min-heap of size k

1import heapq23def kth_largest(nums, k):4    heap = []5    for x in nums:6        heapq.heappush(heap, x)7        if len(heap) > k:8            heapq.heappop(heap)   # drop the smallest9    return heap[0]

The template, filled in for Kth Largest Element in an Array. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchHeap Priority Queue, explainedNeetCode · YouTube · free↗¶ReadBinary heapWikipedia · free↗

Practice set

Loading your mission…

Common mistakes

1Using a max-heap of all n items for k-th largest: works, but O(n log n) and O(n) space.

2Python's heapq is a min-heap; push negatives for a max-heap.

3Sorting the whole list when only the top k are needed.

Check yourself

Question 1 of 2

For the k-th largest number, keep a heap of size k that is a…