Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1-9 must occur exactly once in each row.1-9 must occur exactly once in each column.1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.The '.' character indicates empty cells.
Example 1:
Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] Explanation: The input board is shown above and the only valid solution is shown below:![]()
Constraints:
board.length == 9board[i].length == 9board[i][j] is a digit or '.'.Problem Overview: You are given a partially filled 9x9 Sudoku board. Empty cells are marked with '.'. Fill the board so each row, column, and 3x3 subgrid contains digits 1 through 9 exactly once. The solution must modify the board in-place.
Approach 1: Backtracking (Exponential Time, O(9^k) time, O(81) space)
This problem is a classic use case for backtracking. Iterate through the grid to find the next empty cell. For that position, try digits 1-9. For each candidate, check whether the digit already exists in the same row, column, or 3x3 box. If the placement is valid, write the digit and recursively attempt to solve the remaining board. If the recursive call fails, undo the placement and try the next digit.
The key insight is that invalid partial boards can be detected early, which prunes large parts of the search tree. Validity checks scan the row, column, and subgrid using simple loops over the array or matrix. In the worst case, each empty cell tries 9 digits, giving roughly O(9^k) time where k is the number of blanks. Space complexity is O(81) due to recursion depth and the board itself.
Approach 2: Constraint Propagation + Backtracking (O(9^k) worst-case, O(81) space)
A more optimized approach maintains fast lookup structures to track used digits. Instead of scanning rows and columns repeatedly, store three sets (or boolean arrays): rows[9], cols[9], and boxes[9]. Each structure records which digits are already used. This effectively turns validity checks into constant-time lookups using a hash table or fixed-size arrays.
When placing a digit, update the corresponding row, column, and box structures. During backtracking, remove the digit from those structures. This reduces repeated scanning of the grid and significantly lowers constant factors. Some implementations also choose the next cell with the fewest candidate digits, further reducing branching.
The theoretical complexity remains exponential because Sudoku solving is a constraint satisfaction problem. However, constraint propagation dramatically speeds up real-world cases by pruning invalid choices earlier and performing O(1) constraint checks.
Recommended for interviews: Interviewers expect a clean backtracking solution. Start with the basic recursive search to demonstrate understanding of constraint validation. Strong candidates optimize it using row/column/box tracking to avoid repeated scans. The optimized version shows practical mastery of backtracking combined with efficient data structures.
The backtracking approach is a classic method to solve problems like Sudoku that require exploring all configurations to find a valid solution. This involves recursively trying all numbers from 1 to 9 in each cell and verifying if they meet Sudoku rules. If a number fits, move to the next cell. If stuck, backtrack to the previous cell and try a different number. This method ensures all constraints are respected at each step.
This solution implements a backtracking algorithm in C. The isValid function checks if placing a digit in a particular cell violates Sudoku rules. The solveSudokuHelper function tries placing digits and uses recursion to backtrack if necessary until the board is completely filled.
C++
Java
Python
C#
JavaScript
Time Complexity: O(9^(N*N)), where N = 9 (the size of the board), as each empty cell has 9 possibilities.
Space Complexity: O(N*N) for the recursion stack.
This approach enhances the basic backtracking method by introducing constraint propagation. Before choosing a number for a cell, it checks constraints upfront, reducing unnecessary exploration by propagating constraints once a number is filled. This technique decreases the number of options that need to be tried, thereby optimizing the backtracking process.
This Python solution incorporates constraint propagation into the backtracking method. It attempts to minimize choices by evaluating constraints before any number is placed, helping to reduce the branching factor in the search tree. If a valid scenario is found using propagation, it progresses further in solving the Sudoku.
Time Complexity: Expected better than O(9^(N*N)), depending on effectiveness of constraint propagation reducing possible combinations.
Space Complexity: O(N*N), influenced by recursion.
| Approach | Complexity |
|---|---|
| Backtracking Approach | Time Complexity: O(9^(N*N)), where N = 9 (the size of the board), as each empty cell has 9 possibilities. |
| Constraint Propagation with Backtracking | Time Complexity: Expected better than O(9^(N*N)), depending on effectiveness of constraint propagation reducing possible combinations. |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Backtracking | O(9^k) | O(81) | Standard recursive solution for Sudoku. Good for interviews to demonstrate backtracking and constraint checking. |
| Constraint Propagation + Backtracking | O(9^k) worst-case | O(81) | Preferred implementation when optimizing validity checks using row/column/box tracking structures. |
Valid Sudoku - Amazon Interview Question - Leetcode 36 - Python • NeetCode • 391,868 views views
Watch 9 more video solutions →Practice Sudoku Solver with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor