Problem Statement

Sudoku Solver

Sudoku is a 9 by 9 grid. Some cells already have a digit, and some are empty, shown here as a dot ('.'). The job is to fill every empty cell with a digit from 1 to 9 so that three rules hold: each row has all nine digits with no repeats, each column has all nine digits with no repeats, and each of the nine small 3x3 boxes has all nine digits with no repeats. We solve it with backtracking. Backtracking means: make a guess, follow it as far as you can, and if it leads to a dead end, undo the guess and try a different one. It is like solving a maze where, whenever you hit a wall, you walk back to the last fork and take another path. To check a guess fast, we keep a set (a collection with no duplicates that answers "is this in here?" instantly) for each row, column, and box, so every check is O(1), meaning constant time no matter how full the board is.

hardBacktrackingBacktrackingTime: 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.

Trace it on board: first empty cell at (0,2); rows[0]={5,3,7}, cols[2]={8}, boxes[0]={5,3}

scan finds first '.' at (0,2); box_idx=(0//3)*3+2//3=0
try d='1': not in rows[0]/cols[2]/boxes[0] -> place '1', add to rows[0],cols[2],boxes[0]; recurse solve()
recursion hits a later cell with no valid digit -> that frame returns False; unwind to (0,2)
backtrack (0,2): board[0][2]='.', remove '1' from the three sets; try next d
try d='2': not in rows[0]={5,3,7}/cols[2]={8}/boxes[0]={5,3} -> valid -> place '2', add to sets; recurse (note: '3' would be skipped since it's in rows[0] and boxes[0])
deeper recursion eventually fills last '.' -> innermost solve() returns True
True propagates up every frame, each keeping its placed digit; outer solve() returns True
board fully filled and consistent (each row/col/box holds 1-9); returned: solved board in-place

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.

Shape of the loop

build rows[9], cols[9], boxes[9] sets from given digits
solve(): scan for first '.' cell (i,j); if none -> return True
  box = (i//3)*3 + j//3
  for d in '1'..'9':
    if d not in rows[i],cols[j],boxes[box]:
      place d; add d to all three sets
      if solve(): return True
      erase d; remove d from all three sets   # backtrack
  return False  # no digit fit -> backtrack to caller

Pseudocode only — the full worked solution lives in the Solution tab.

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