DSA Notes
Build a complete Sudoku solver using backtracking with constraint propagation — validate placements across rows, columns, and 3×3 boxes, and backtrack on conflicts.
Problem Statement
Fill a 9×9 grid so that each row, each column, and each of the nine 3×3 sub-boxes contains all digits from 1 to 9 exactly once. Given a partially filled board (with zeros representing empty cells), find a valid completion.
Why Backtracking Works Here
Sudoku is a classic constraint satisfaction problem. At each empty cell, we try digits 1-9. Before placing a digit, we check whether it violates any constraint. If all digits 1-9 are invalid for a cell, we have reached a dead end and must backtrack to the previous cell and try its next candidate.
The key insight: constraints are checkable in O(1) per placement if we maintain sets of used digits for each row, column, and box. This fast validation combined with early backtracking makes the solver efficient despite the theoretical exponential search space.
Constraint Validation
A digit d is safe to place at position (row, col) if:
dis not already inrow→ checkrow_sets[row]dis not already incol→ checkcol_sets[col]dis not already in the 3×3 box → checkbox_sets[box_index]
The box index is computed as: box_index = (row // 3) * 3 + (col // 3)
Algorithm Steps
- Find the next empty cell (scanning left-to-right, top-to-bottom).
- If no empty cell exists, the puzzle is solved — return True.
- For digits 1 through 9:
a. Check if the digit is valid (not in same row, column, or box). b. If valid, place the digit and recurse to solve the rest. c. If recursion succeeds, propagate success upward. d. If recursion fails, remove the digit (backtrack) and try the next.
- If no digit works, return False (triggers backtracking in the caller).
Python Implementation
Optimized Version with Sets
The naive is_valid scans the row, column, and box on each call (O(9) each). Using precomputed sets reduces validation to O(1):
C++ Implementation
Constraint Propagation (Advanced)
Before brute-force backtracking, reduce the search space:
- Naked singles: If a cell has only one possible digit, place it immediately.
- Hidden singles: If a digit can go in only one place in a row/col/box, place it.
- Elimination: When placing a digit, eliminate it from peers' candidate lists.
This is the technique used by Peter Norvig's famous Sudoku solver. It solves most "easy" and "medium" puzzles without any backtracking at all, leaving backtracking only for the hardest cases.
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Worst-case time | O(9^E) | E = number of empty cells (max 81). Each cell tries up to 9 digits. |
| Practical time | ~10,000 nodes | With constraint sets, most puzzles solve in milliseconds |
| Space | O(81) = O(1) | Fixed grid size, recursion depth ≤ 81 |
The 9^81 theoretical worst case never occurs in valid Sudoku puzzles because constraints prune the tree aggressively.
Real-World Applications
- Puzzle apps: The algorithm behind Sudoku solvers in mobile apps
- Constraint solvers: Same technique applies to scheduling, timetabling, and resource allocation
- SAT solvers: Sudoku reduces to Boolean satisfiability — industrial SAT solvers use similar backtrack-with-propagation
- Verification: Checking uniqueness of puzzles (a valid puzzle has exactly one solution)
Key Takeaways
Sudoku solving demonstrates backtracking at its most structured: fixed-size search space, easily-checkable constraints, and massive pruning potential. The pattern — find empty cell, try candidates, validate, recurse, undo — transfers directly to any constraint satisfaction problem. Precomputing constraint sets (rows/cols/boxes) transforms validation from O(N) to O(1), which makes a significant practical difference.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Sudoku Solver.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, backtracking, sudoku, solver
Related Data Structures & Algorithms Topics