21. Heaps & Priority Queue

Top K, k-way merge and the two-heap median pattern.

🎬 Episodes 64–68: video coming soon
Your progress0 of 13
2easy
8medium
3hard

Understand the topic

A heap always gives you the smallest (min-heap) or largest (max-heap) item in O(1), and adding or removing costs O(log n). In Java it's PriorityQueue, which is a min-heap by default; use Collections.reverseOrder() or a comparator for a max-heap.

Three patterns cover most questions. For Top K, keep a heap of size k, and the top is your boundary. For a K-way merge, put the head of each list in a heap and always take the smallest. For a running median, use two heaps that each hold half of the numbers.

#ProblemPatternLevel
1 Kth Largest Element in a Stream #703 Min-heap of size k Easy LeetCode β†—
2 Last Stone Weight #1046 Max-heap simulation Easy LeetCode β†—
3 Kth Largest Element in an Array #215 Min-heap / quickselect Medium LeetCode β†—
4 Top K Frequent Elements #347 Bucket sort by frequency Medium LeetCode β†—
5 K Closest Points to Origin #973 Max-heap of size k Medium LeetCode β†—
6 Top K Frequent Words #692 Heap with a two-key comparator Medium LeetCode β†—
7 Task Scheduler #621 Greedy counting Medium LeetCode β†—
8 Reorganize String #767 Max-heap, place two at a time Medium LeetCode β†—
9 Kth Smallest Element in a Sorted Matrix #378 K-way merge with a min-heap Medium LeetCode β†—
10 Furthest Building You Can Reach #1642 Min-heap of climbs given ladders Medium LeetCode β†—
11 Find Median from Data Stream #295 Two heaps Hard LeetCode β†—
12 IPO #502 Sort by capital + max-heap of profits Hard LeetCode β†—
13 Smallest Range Covering Elements from K Lists #632 Min-heap with running max Hard LeetCode β†—

Work top to bottom β€” each list goes from easy to hard. Try a problem for at least 15 minutes before opening a hint. Ticks are saved in your browser.