hardBacktrackingBacktracking

Sudoku Solver

hardTime: O(9^m)Space: O(m)

Signals to notice

fill 9×9 grid satisfying constraintsempty cells to fillconstraint propagation + backtracking

Brute force first

Try all 9^(empty cells) combinations — astronomical. No pruning. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Backtracking: for each empty cell, try digits 1-9. Check row, column, and 3×3 box constraints. If valid, recurse to next empty cell. If stuck, backtrack. worst case where m = empty cells, but pruning makes it practical. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

At each empty cell, try only valid digits (not already in the same row, column, or box). This constraint checking prunes the vast majority of branches. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not precomputing which digits are available — checking constraints via sets/arrays for each row, column, and box speeds up the validity check from to. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Backtracking Pattern