Solve ANY Backtracking Problem on Leetcode
Channel: Bitflip
Watch on YouTube →Algorithm • hard
Backtracking explores a decision tree by trying choices, recursing, then undoing choices when constraints fail.
It is essential for permutation/combination/search problems with combinatorial explosion.
Performance depends heavily on pruning and candidate ordering.
Typical Complexity Baseline
| Metric | Value |
|---|---|
| Complexity Note 1 | Often exponential in worst case |
See It
A small animated SVG that illustrates the core idea the moving parts you need to keep in your head when you read the rest of the guide.
Failed branches are pruned (✕) so we do not waste work below them.
Watch First
A quick visual walkthrough before the detailed sections pick the format that helps you learn fastest.
Channel: Bitflip
Watch on YouTube →Mechanics
The building blocks and terminology you need before everything else clicks. Skim or deep-read.
What it is Implicit tree of candidate choices.
Why it matters Decision tree is a required building block for understanding how Backtracking stays correct and performant on large inputs.
What it is Current partial solution.
Why it matters State is a required building block for understanding how Backtracking stays correct and performant on large inputs.
What it is Available next options from current state.
Why it matters Choice set is a required building block for understanding how Backtracking stays correct and performant on large inputs.
What it is Pruning condition to stop invalid branches early.
Why it matters Constraint check is a required building block for understanding how Backtracking stays correct and performant on large inputs.
What it is Revert state after recursive call returns.
Why it matters Undo step is a required building block for understanding how Backtracking stays correct and performant on large inputs.
What it is Discard branch that cannot lead to valid/optimal solution.
Why it matters Discard branch that cannot lead to valid/optimal solution. In Backtracking, this definition helps you reason about correctness and complexity when inputs scale.
What it is Average number of child choices per level.
Why it matters Average number of child choices per level. In Backtracking, this definition helps you reason about correctness and complexity when inputs scale.
What it is Number of choices made so far.
Why it matters Number of choices made so far. In Backtracking, this definition helps you reason about correctness and complexity when inputs scale.
What it is Update remaining options based on recent choices.
Why it matters Update remaining options based on recent choices. In Backtracking, this definition helps you reason about correctness and complexity when inputs scale.
What it is Tree of partial configurations explored by algorithm.
Why it matters Tree of partial configurations explored by algorithm. In Backtracking, this definition helps you reason about correctness and complexity when inputs scale.
Walkthrough
Every frame of the concept diagram, laid out top-to-bottom so you can scroll through the algorithm at your own pace.
Start at ∅. Try each choice; recurse; undo on failure.
Pick 1. Partial: [1].
Pick 2. [1, 2] is a valid permutation. Record.
Backtrack to [1]. Undo the 2.
Pick 3. Constraint says no prune ✕.
Backtrack to ∅.
Try the other branch. Pick 2.
Pick 1. [2, 1] is valid. Record.
Backtrack, try 3. Pruned ✕. Search complete.
Tradeoffs
When this technique wins, when it loses, and what to reach for instead.
Choose this when Choose backtracking when full solution enumeration is needed.
Tradeoff DP is better for overlapping-subproblem optimization tasks.
Choose this when Choose backtracking when local choices can invalidate future feasibility.
Tradeoff Greedy is faster when provably correct.
Choose this when Choose backtracking for structured recursive search and pruning hooks.
Tradeoff Still exponential in worst case without strong pruning.
In Production
Where this shows up at real companies and what the on-call engineer learned the hard way.
Scheduling and assignment engines rely on backtracking + pruning when constraints are complex.
Takeaway Backtracking is practical when exactness matters.
Puzzle generation/validation often explores candidate states recursively.
Takeaway Search-tree control is crucial in content tooling.
Policy and configuration validation may recursively explore rule combinations.
Takeaway Backtracking helps enumerate valid safe configurations.
Code
A clean reference implementation in TypeScript, Python, and Go. Switch languages with the toggle.
Choose unused element, recurse, then undo to explore next branch.
Complexity: Time O(n! * n), Space O(n)
Generate permutations
function permutations(values: number[]): number[][] {
const result: number[][] = []
const currentPath: number[] = []
const usedByIndex = new Array<boolean>(values.length).fill(false)
function dfs(): void {
if (currentPath.length === values.length) {
result.push([...currentPath])
return
}
for (let valueIndex = 0; valueIndex < values.length; valueIndex += 1) {
if (usedByIndex[valueIndex]) continue
usedByIndex[valueIndex] = true
currentPath.push(values[valueIndex])
dfs()
currentPath.pop()
usedByIndex[valueIndex] = false
}
}
dfs()
return result
}
Watch Out
The bugs and edge cases that bite engineers most often. Skim before you ship.
Pro Tips
Small habits that pay off every time you reach for this pattern.
Pattern Recognition
Concrete signals that tell you this is the right pattern both at work and on LeetCode.
Practice
A curated easy-to-hard problem ladder. Each one reinforces a specific aspect of the pattern.
| # | Problem | Difficulty | Typical Complexity |
|---|---|---|---|
| 1 | Subsets | Medium | O(n*2^n) |
| 2 | Combination Sum | Medium | Exponential |
| 3 | Permutations | Medium | O(n*n!) |
| 4 | Generate Parentheses | Medium | Catalan |
| 5 | Palindrome Partitioning | Medium | Exponential |
| 6 | Word Search | Medium | O(m*n*4^L) |
| 7 | N-Queens | Hard | Exponential |
| 8 | Sudoku Solver | Hard | Exponential |
| 9 | Word Search II | Hard | Pruned DFS |
| 10 | Expression Add Operators | Hard | Exponential |