Lesson 23 of 27Decode by category
Decoding Backtracking and Heaps
Spot backtracking from 'all possible' and tiny constraints, and heaps from k-th, top k, merge k, schedules, and streams.
Backtracking and heaps look unrelated, but they get decoded the same way: from a handful of very reliable words. "Return all possible" almost always means backtracking. "K-th largest", "top k", and "merge k" almost always mean a heap. Learn the words and the constraint sizes that go with them, and these become some of the fastest problems to classify. Backtracking and Heaps in the Algorithms & Patterns course teach the templates; this lesson is only about spotting them.
Backtracking: when the answer is every answer
Backtracking builds candidates one choice at a time, and undoes the last choice to try the next one. It explores a tree of decisions.
Every node in this tree is a subset. The root is the empty choice.
The clues
| Wording | Meaning |
|---|---|
| "return all possible", "list every", "generate all" | The output is the full set of answers. |
| "combinations", "permutations", "subsets", "partitions" | Classic decision trees. |
| "place n queens", "solve the Sudoku", "fill the board" | Constraint search with pruning. |
| "word search in a grid" | Path search that undoes visited marks. |
The constraint tell
Backtracking is exponential, and that is fine only because the input is tiny. If you see these limits next to "all", it is a strong confirmation:
| Constraint | Search size | Fits? |
|---|---|---|
n <= 10 | n! is about 3.6 million | Permutations OK |
n <= 20 | 2ⁿ is about a million | Subsets OK |
n <= 10^3 or more | 2ⁿ is astronomical | Not backtracking. Look for DP or greedy. |
If the prompt says "how many" instead of "list all" and n is large, the decoder in your head should switch to DP. The previous lesson covered that split.
Press Run (⌘ Enter) to see what happens.What does this print?
print(len(subsets([5, 6, 7, 8, 9])))
Put the backtracking loop body in order.
- Tap the steps below in the right order.
Heaps: when you only care about the extremes
A heap is a tree kept in an array where every parent is smaller than its children (a min-heap). The smallest item is always at the top. Adding or removing costs O(log n), and peeking at the top is O(1). Python's heapq and a priority queue in most languages are heaps.
The root is the minimum. Peeking at it is O(1).
The clues
| Wording | Heap move |
|---|---|
| "k-th largest", "k-th smallest" | Keep a heap of size k. The top is the answer. |
| "top k", "k most frequent", "k closest" | Same: a size-k heap, O(n log k). |
| "merge k sorted lists / arrays" | Heap of the k current heads. Pop the smallest, push its successor. |
| "schedule", "tasks", "rooms", "CPU", "servers" | Heap of next-free times or of available tasks. |
| "stream", "data arrives one at a time", "running median" | Heap(s) maintained online. Two heaps for a median. |
| "repeatedly take the largest / smallest" | Simulate with a heap (Last Stone Weight). |
The trick with "k-th largest" catches people: you use a min-heap of size k. Every time it grows past k, pop the smallest. What remains are the k largest, and the smallest of those, at the top, is the k-th largest.
What does this print?
import heapq
nums = [5, 1, 9, 3, 7]
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > 2:
heapq.heappop(heap)
print(heap[0])Neighbours to rule out
| Looks like | But actually | Deciding clue |
|---|---|---|
| "k-th smallest in a sorted matrix" | Heap or binary search on the value | Rows and columns sorted: both work, say both |
| "k most frequent" | Heap, or bucket sort for O(n) | Frequencies are bounded by n |
| "number of subsets that sum to k" | DP, not backtracking | "number of", large n |
| "sliding window maximum" | Monotonic deque, not heap | Window plus max: the deque is O(n), a heap O(n log n) |
| "all paths from source to target in a DAG" | Backtracking (DFS with a path) | "all paths" means list them |
Match each prompt to its approach.
nums whose sum equals target.' Constraint: 1 <= nums.length <= 200. What should you say first?Run a few heap and backtracking problems through the Decoder. In the constraint stage, say the search size out loud (2ⁿ, n!, n log k) before you reveal the target.
Subsets
Given a list of distinct integers nums, return every possible subset (the power set). Include the empty subset and the full list. The subsets, and the numbers inside each one, can be in any order, but no subset may appear twice.
[1, 2, 3] → [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
[0] → [[], [0]]Constraints
0 <= nums.length <= 10-10 <= nums[i] <= 10- All the numbers in
numsare distinct.
Kth Largest Element
Given a list of integers nums and a number k, return the kth largest value. This is the kth largest in sorted order, so duplicates count separately.
nums = [3, 2, 1, 5, 6, 4], k = 2 → 5
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 → 4Try to beat sorting the whole list.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
- backtracking
- Building answers one choice at a time and undoing the last choice to try the next.
- pruning
- Stopping a branch early once it cannot lead to a valid answer.
- heap
- A tree in an array where each parent is smaller (min-heap) or larger (max-heap) than its children.
- size-k heap
- A heap trimmed to k items, giving top k or the k-th largest in O(n log k).
- two heaps
- A max-heap for the lower half and a min-heap for the upper half, used for a running median.