Skip to content

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.

15 min read0/6 questions

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.

Decision tree for subsets of [1, 2, 3]
[]start empty[1,2,3]then 3[1,2]then 2[1,3]skip 2, choose 3[1]choose 1[2,3]then 3[2]start from 2[3]start from 3root

Every node in this tree is a subset. The root is the empty choice.

1/4

The clues

WordingMeaning
"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:

ConstraintSearch sizeFits?
n <= 10n! is about 3.6 millionPermutations OK
n <= 202ⁿ is about a millionSubsets OK
n <= 10^3 or more2ⁿ is astronomicalNot 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.

Pythonsubsets.py
def subsets(nums: list[int]) -> list[list[int]]: out: list[list[int]] = [] path: list[int] = [] def go(start: int) -> None: out.append(path[:]) # record a copy for i in range(start, len(nums)): path.append(nums[i]) # choose go(i + 1) # explore path.pop() # undo go(0) return out print(subsets([1, 2, 3]))print(len(subsets([1, 2, 3, 4])))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

print(len(subsets([5, 6, 7, 8, 9])))
Need a nudge? Hints walk you through it.
Put it in order5 steps

Put the backtracking loop body in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

A min-heap: the smallest is always on top
734152

The root is the minimum. Peeking at it is O(1).

1/3

The clues

WordingHeap 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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.
Quick check
Top k from n = 10^6 values with k = 10. Why prefer a size-k heap over sorting?
Need a nudge? A hint rules out a wrong answer.

Neighbours to rule out

Looks likeBut actuallyDeciding clue
"k-th smallest in a sorted matrix"Heap or binary search on the valueRows 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 heapWindow 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 the pairs0/6 matched

Match each prompt to its approach.

Choose an item, then its match on the other side.
Quick check
'Return all subsets of nums whose sum equals target.' Constraint: 1 <= nums.length <= 200. What should you say first?
Need a nudge? A hint rules out a wrong answer.

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.

ChallengeMedium

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 nums are distinct.
def subsets(nums: list[int]) -> list[list[int]]: # For each number, branch twice: leave it out, or take it. pass
ChallengeMedium

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  →  4

Try to beat sorting the whole list.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
def find_kth_largest(nums: list[int], k: int) -> int: # Keep only the k largest values seen so far in a min-heap. pass
Key terms
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.