Tensorum
LeetCode 37 · Constraint Satisfaction

Sudoku Solver

LeetCode 37 · Hard · solution, intuition & step-by-step walkthrough

Backtracking over empty cells with a validity check.

HardArrayHash TableBacktrackingMatrixAlgorithm X
499 msruntime · beats 62%
56.8 MBmemory · beats 69%
1approach
11accepted runs · last 3 Mar 2026

This is how I solved Sudoku Solver (LeetCode 37), a hard problem from the Constraint Satisfaction pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Find the first empty cell and try digits 1–9 that don't clash with its row, column or 3×3 box. Place one and recurse; if the rest of the board can't be solved, undo it and try the next digit.

Approach

  1. 1

    Scan for an empty cell.

  2. 2

    Try each digit that is valid for its row, column and box.

  3. 3

    Recurse; on failure, reset the cell.

  4. 4

    No digit works → return False; no empty cell → solved.

How I solved it

BacktrackingPythonexponential worst case
class Solution:
    def solveSudoku(self, board):
        def isValid(row, col, k, board):
            for i in range(9):
                if board[row][i] == k:
                    return False
                if board[i][col] == k:
                    return False
                if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == k:
                    return False
            return True

        def solve(board):
            for row in range(9):
                for col in range(9):
                    if board[row][col] == ".":
                        for k in range(1, 10):
                            charK = str(k)
                            if isValid(row, col, charK, board):
                                board[row][col] = charK
                                if solve(board):
                                    return True
                                else:
                                    board[row][col] = "."
                        return False
            return True
        solve(board)
Loading the step-through…

Sudoku Solver — FAQ

What is the intuition behind Sudoku Solver?

Find the first empty cell and try digits 1–9 that don't clash with its row, column or 3×3 box. Place one and recurse; if the rest of the board can't be solved, undo it and try the next digit.

How do you solve Sudoku Solver (LeetCode 37)?

1. Scan for an empty cell. 2. Try each digit that is valid for its row, column and box. 3. Recurse; on failure, reset the cell. 4. No digit works → return False; no empty cell → solved.

What is the time and space complexity of Sudoku Solver?

Time: O(9^m) for m empty cells. Space: O(m) recursion. (Accepted approach: Backtracking.)

What are common mistakes in Sudoku Solver?

The box index is 3·(row//3) + i//3, 3·(col//3) + i%3.