Py

Heaps & Top-K

Unit 10 of 15
⛰️

Core Patterns

Heaps & Top-K

Always know the smallest (or largest) item in O(1) and update in O(log n). Heaps power top-k, k-way merge, running medians and schedulers.

0 of 3 lessons complete, 0 of 7 problems solved

Start unitPattern cheatsheet

Coursework

37 min

1
Up next

What a Heap Is

A complete binary tree packed into a list that keeps the minimum on top.

11 min
2

heapq: Max-Heaps, Priorities and Top-K

Drive Python's min-heap like a pro and keep the k best items in O(n log k).

13 min
3

K-Way Merge, Two Heaps and Scheduling

Three heap patterns that show up again and again in interviews.

13 min

Practice ladder

Start with the first problem, then work toward the harder variations. Run examples before submitting against all tests.

1.Last Stone Weight

Smash the two heaviest stones together until at most one is left.

EasyLC #1046
2.Kth Largest Element in a Stream

Report the k-th largest score after every new score arrives.

EasyLC #703
3.Kth Largest Element in an Array

Find the k-th largest number without fully sorting.

MediumLC #215
4.K Closest Points to Origin

Return the k points nearest to (0, 0).

MediumLC #973
5.Task Scheduler

Schedule tasks with a cooldown between repeats using as few time slots as possible.

MediumLC #621
6.Merge K Sorted Arrays

Merge k sorted lists of numbers into one sorted list.

MediumLC #23
7.Find Median from Data Stream

Support adding numbers and reading the running median quickly.

HardLC #295
Next unit: Backtracking