Algorithms
Backtracking
๐ At a Glance
| Aspect | Details |
|---|---|
| Time to Read | 35 minutes |
| Prerequisites | Part 2 (Recursion), Part 16 (DP basics) |
| Key Concepts | Backtracking Template, Pruning, N-Queens, Sudoku, Branch & Bound |
| Difficulty | โญโญโญ (Intermediate) |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ BACKTRACKING โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ EXPLORE โ CHOOSE โ EXPLORE โ BACKTRACK โ โ โ โ โ root โ โ / | \ โ โ โ โ โ Level 1: choices โ โ /| | |\ โ โ โ โ ร โ โ Level 2: ร = pruned (invalid) โ โ /| | |\ โ โ โ ร โ ร โ Level 3: leaves = solutions โ โ โ โ Key insight: Don't explore paths that can't lead to solution โ โ โ โ Template: โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ backtrack(state): โ โ โ โ if isComplete(state): โ โ โ โ addToResults(state) โ โ โ โ return โ โ โ โ โ โ โ โ for choice in getChoices(state): โ โ โ โ if isValid(choice): โ โ โ โ makeChoice(choice) โ โ โ โ backtrack(state) โ โ โ โ undoChoice(choice) โ KEY STEP โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฏ What You'll Learn
After completing this article, you will be able to:
- Apply the backtracking template: Systematic approach for any problem
- Solve classic problems: N-Queens, Sudoku, permutations
- Prune effectively: Cut search space dramatically
- Use branch and bound: Optimization with bounds
- Choose between approaches: Backtracking vs DP vs brute force
๐ฅ Production Story: The Configuration Solver
A network equipment company needed to find valid configurations for complex hardware setups with many constraints.
The Problem
JAVA(15 lines)CodeLoading syntax highlighter...
The Solution: Backtracking with Constraint Propagation
JAVA(48 lines)CodeLoading syntax highlighter...
The Impact
| Metric | Brute Force | Backtracking |
|---|---|---|
| Search space | 10^50 | ~10^6 (pruned) |
| Time for solution | Impossible | 0.3 seconds |
| Memory | N/A | O(depth) |
| Valid configs found | 0 | 847 |
๐ง Mental Model: The Maze Explorer
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ BACKTRACKING AS MAZE EXPLORATION โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ โโโโโฌโโโโฌโโโโฌโโโโฌโโโโ โ โ โ S โ โ โ โ โ โ S = Start โ โ โโโโโผโโโโผโโโโผโโโโผโโโโค E = End (goal) โ โ โ โ โ โ โ โ โ โ = Wall (invalid) โ โ โโโโโผโโโโผโโโโผโโโโผโโโโค ยท = Path tried โ โ โ โ โ โ โ โ โ โ = Current position โ โ โโโโโผโโโโผโโโโผโโโโผโโโโค โ โ โ โ โ โ โ โ โ โ โ โ โโโโโผโโโโผโโโโผโโโโผโโโโค โ โ โ โ โ โ โ E โ โ โ โโโโโดโโโโดโโโโดโโโโดโโโโ โ โ โ โ Algorithm: โ โ 1. From current position, try each direction โ โ 2. If direction leads to wall or visited โ skip (prune) โ โ 3. Move to new position, mark as visited โ โ 4. If at goal โ found solution! โ โ 5. If stuck โ go back (backtrack), try next direction โ โ โ โ Key: Marking visited prevents infinite loops โ โ Backtracking undoes the "visited" mark โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฌ Deep Dive: The Backtracking Template
General Template
JAVA(35 lines)CodeLoading syntax highlighter...
Subsets (Power Set)
JAVA(20 lines)CodeLoading syntax highlighter...
Permutations
JAVA(59 lines)CodeLoading syntax highlighter...
Combinations
JAVA(51 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: N-Queens Problem
The Problem
Place N queens on an NรN chessboard so no two attack each other.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ N-QUEENS (N=4) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Solution 1: Solution 2: โ โ โโโโโฌโโโโฌโโโโฌโโโโ โโโโโฌโโโโฌโโโโฌโโโโ โ โ โ โ Q โ โ โ โ โ โ Q โ โ โ โ โโโโโผโโโโผโโโโผโโโโค โโโโโผโโโโผโโโโผโโโโค โ โ โ โ โ โ Q โ โ Q โ โ โ โ โ โ โโโโโผโโโโผโโโโผโโโโค โโโโโผโโโโผโโโโผโโโโค โ โ โ Q โ โ โ โ โ โ โ โ Q โ โ โ โโโโโผโโโโผโโโโผโโโโค โโโโโผโโโโผโโโโผโโโโค โ โ โ โ โ Q โ โ โ โ Q โ โ โ โ โ โโโโโดโโโโดโโโโดโโโโ โโโโโดโโโโดโโโโดโโโโ โ โ โ โ Constraint: No two queens share row, column, or diagonal โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implementation
JAVA(84 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Sudoku Solver
Implementation
JAVA(109 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Branch and Bound
The Concept
Branch and Bound adds bounding functions to prune branches that can't improve on the best solution found so far.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ BRANCH AND BOUND โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Standard Backtracking: โ โ - Prunes invalid solutions โ โ โ โ Branch and Bound (for optimization): โ โ - Also prunes solutions that can't beat current best โ โ โ โ Components: โ โ 1. Branch: Split problem into subproblems โ โ 2. Bound: Calculate optimistic estimate for subtree โ โ 3. Prune: If bound โค best found, skip this branch โ โ โ โ Example for minimization: โ โ โ โ Current best = 50 โ โ โ โ โ / | \ โ โ โ โ โ โ โ lb=30 lb=55 lb=40 โ โ โ โ โ lb=55 > 50, prune! โ โ explore explore โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
TSP with Branch and Bound
JAVA(84 lines)CodeLoading syntax highlighter...
0/1 Knapsack with Branch and Bound
JAVA(70 lines)CodeLoading syntax highlighter...
โ ๏ธ Common Mistakes
Mistake 1: Forgetting to Undo Choice
JAVA(17 lines)CodeLoading syntax highlighter...
Mistake 2: Modifying Loop Variable
JAVA(17 lines)CodeLoading syntax highlighter...
Mistake 3: Adding Reference Instead of Copy
JAVA(17 lines)CodeLoading syntax highlighter...
๐ Debug This: Permutation Bug
This permutation generator has a bug. Can you find it?
JAVA(21 lines)CodeLoading syntax highlighter...
๐ Click to reveal the bug
Bug: Using
contains(nums[i]) to check if element is used. This fails when array has duplicates!JAVA(22 lines)CodeLoading syntax highlighter...
Example where bug manifests:
nums = [1, 1, 2] Bug: "1 is already in current" - skips valid permutations Result: Missing [1,1,2], [1,2,1], [2,1,1]
๐ป Exercises
Exercise 1: Generate Parentheses โญโญ
Generate all valid combinations of n pairs of parentheses.
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 2: Letter Combinations of Phone โญโญ
Given digits 2-9, return all letter combinations (like phone keypad).
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 3: Word Search โญโญโญ
Find if word exists in 2D grid (adjacent cells, no reuse).
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 4: Palindrome Partitioning โญโญโญ
Partition string so every substring is a palindrome.
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 5: Expression Add Operators โญโญโญโญ
Add +, -, * between digits to reach target.
JAVA(3 lines)CodeLoading syntax highlighter...
๐ค Interview Questions
Q1: "What's the difference between backtracking and DFS?"
Answer:
DFS is a traversal technique. Backtracking uses DFS but with:
- State modification: Change state before recursing
- State restoration: Undo changes after recursing
- Pruning: Skip invalid branches early
JAVA(20 lines)CodeLoading syntax highlighter...
Q2: "How do you optimize backtracking?"
Answer:
-
Pruning: Skip invalid branches earlyJAVACodeLoading syntax highlighter...
-
Ordering: Try most constrained choice firstJAVACodeLoading syntax highlighter...
-
Constraint propagation: Reduce choices after each decisionJAVACodeLoading syntax highlighter...
-
Symmetry breaking: Avoid equivalent solutionsJAVACodeLoading syntax highlighter...
-
Memoization: Cache repeated subproblemsJAVACodeLoading syntax highlighter...
Q3: "When should I use backtracking vs DP?"
Answer:
| Backtracking | DP |
|---|---|
| Find all solutions | Find optimal/count |
| Solutions have structure (permutation, subset) | Overlapping subproblems |
| Constraints are complex | State can be compactly represented |
| O(b^d) where b=branching, d=depth | Polynomial if states are polynomial |
Rule of thumb:
- Need all solutions โ Backtracking
- Need count/optimal โ Try DP first
- Can't define subproblems โ Backtracking
Q4: "Explain the N-Queens problem and optimize it."
Answer:
JAVA(27 lines)CodeLoading syntax highlighter...
Q5: "How does branch and bound improve over basic backtracking?"
Answer:
Branch and bound adds bounding functions for optimization problems:
Backtracking: Prune if state is INVALID Branch & Bound: Prune if state CAN'T IMPROVE on best found For minimization: - Calculate lower bound on solutions in this subtree - If lower_bound >= best_found, prune entire subtree For maximization: - Calculate upper bound - If upper_bound <= best_found, prune Example (TSP): - Current path cost: 50 - Lower bound for remaining: 30 (sum of minimum edges) - Total lower bound: 80 - Best complete tour found: 75 - 80 > 75 โ prune this branch!
๐ Quick Reference
Problem Types
| Problem | Key Insight |
|---|---|
| Subsets | Include/exclude each element |
| Permutations | Track used elements |
| Combinations | Use start index to avoid duplicates |
| N-Queens | Column + 2 diagonal checks |
| Sudoku | Row + column + box constraints |
Complexity
| Problem | Time | Space |
|---|---|---|
| Subsets | O(2^n) | O(n) |
| Permutations | O(n!) | O(n) |
| Combinations(n,k) | O(C(n,k)) | O(k) |
| N-Queens | O(n!) | O(n) |
| Sudoku | O(9^(empty cells)) | O(1) |
Template Summary
JAVA(14 lines)CodeLoading syntax highlighter...
๐ What's Next?
In Part 21: Probabilistic & Approximation Algorithms, we'll explore:
- Randomized algorithms
- Bloom filters
- HyperLogLog
- Approximation algorithms
๐ Review Schedule
| Day | Focus | Time |
|---|---|---|
| 0 | Full read + subsets/permutations | 90 min |
| 1 | Quick Reference | 10 min |
| 3 | N-Queens implementation | 25 min |
| 7 | Sudoku solver | 30 min |
| 14 | Debug exercise + B&B | 20 min |
| 30 | Interview questions | 15 min |
Series: Algorithms Compendium Index