Recursion, trees and heaps · mid
Backtracking
Backtracking builds a solution step by step, tries each choice, recurses, then undoes the choice, which lists all subsets, permutations or combinations, and pruning cuts branches that cannot succeed.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Template: function dfs(state): if done: save a copy of the path; return; for each choice: if not valid: skip; make the choice; dfs(next state); undo the choice.
- Save a COPY of the path (Java new ArrayList<>(path), Python path[:] or list(path)); saving the path itself gives many references to one list that ends up empty.
- Subsets: 2^n; permutations: n!; say the output size, it dominates the complexity.
- Combination sum: sort the candidates, pass a start index to avoid repeated combinations, and stop when a candidate is larger than the remaining sum.
- Pruning: stop early when the partial answer is already invalid (more ')' than '(' in parentheses, remaining sum below 0).
- Duplicates in the input: sort, then skip a value equal to the previous one at the same level (i > start and a[i] == a[i - 1]).
- Typical uses: generate all valid parentheses, 'all sentences' in word break, puzzles such as n-queens and sudoku.
The red pen
Common traps: mistake → fix
Mistake: Saving the path without copying is fine
Fix: later undo steps change it; save a copy.
Mistake: A visited set is enough for permutations of values with duplicates
Fix: sort and skip equal neighbours that were not used.
Mistake: Backtracking is the same as DP
Fix: DP reuses overlapping sub-results; backtracking lists every solution.
Easy to hard
Questions interviewers ask, easy to hard
- Generate all subsets.
- All permutations; what if values repeat?
- Combination sum with unlimited reuse.
- Generate all valid parentheses strings of n pairs; how do you prune?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.