37. Sudoku Solver
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The Sudoku Solver problem is a classic constraint satisfaction puzzle. We need to fill a 9x9 grid with digits 1-9, adhering to three rules: each digit must appear exactly once in each row, each column, and each of the nine 3x3 sub-grids. The problem guarantees a unique solution exists.
Solution
Sudoku Solver in Python
class Solution:
def solveSudoku(self, board: list[list[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# Tracking arrays for used numbers.
rows = [[False] * 10 for _ in range(9)]
cols = [[False] * 10 for _ in range(9)]
boxes = [[False] * 10 for _ in range(9)]
# Initialize tracking arrays from the given board.
for r in range(9):
for c in range(9):
if board[r][c] != '.':
num = int(board[r][c])
rows[r][num] = True
cols[c][num] = True
boxes[(r // 3) * 3 + c // 3][num] = True
# Start backtracking from cell (0, 0).
self.backtrack(board, 0, 0, rows, cols, boxes)
def backtrack(self, board: list[list[str]], r: int, c: int,
rows: list[list[bool]], cols: list[list[bool]], boxes: list[list[bool]]) -> bool:
# Base case: if we have moved past the last row, we have a solution.
if r == 9:
return True
# Calculate coordinates for the next cell.
next_r, next_c = (r, c + 1) if c != 8 else (r + 1, 0)
# If the cell is already filled, move to the next.
if board[r][c] != '.':
return self.backtrack(board, next_r, next_c, rows, cols, boxes)
# Try placing numbers 1-9 in the empty cell.
for num in range(1, 10):
box_idx = (r // 3) * 3 + c // 3
# Check if the placement is valid.
if not rows[r][num] and not cols[c][num] and not boxes[box_idx][num]:
# Place the number.
board[r][c] = str(num)
rows[r][num] = True
cols[c][num] = True
boxes[box_idx][num] = True
# Recurse to the next cell.
if self.backtrack(board, next_r, next_c, rows, cols, boxes):
return True
# Backtrack: undo the placement.
boxes[box_idx][num] = False
cols[c][num] = False
rows[r][num] = False
board[r][c] = '.'
# If no number leads to a solution, return False.
return False
Sudoku Solver in Java
class Solution {
public void solveSudoku(char[][] board) {
// Tracking arrays for used numbers.
boolean[][] rows = new boolean[9][10];
boolean[][] cols = new boolean[9][10];
boolean[][] boxes = new boolean[9][10];
// Initialize tracking arrays based on the initial board.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '0';
rows[i][num] = true;
cols[j][num] = true;
boxes[(i / 3) * 3 + j / 3][num] = true;
}
}
}
// Start backtracking from cell (0, 0).
backtrack(board, 0, 0, rows, cols, boxes);
}
private boolean backtrack(char[][] board, int r, int c,
boolean[][] rows, boolean[][] cols, boolean[][] boxes) {
// Base case: If we have reached the end of the board, solution is found.
if (r == 9) {
return true;
}
// Calculate the coordinates of the next cell.
int next_r = (c == 8) ? r + 1 : r;
int next_c = (c == 8) ? 0 : c + 1;
// If the current cell is already filled, move to the next one.
if (board[r][c] != '.') {
return backtrack(board, next_r, next_c, rows, cols, boxes);
}
// Try placing digits from 1 to 9.
for (int num = 1; num <= 9; num++) {
int box_idx = (r / 3) * 3 + c / 3;
// Check if placing 'num' is valid.
if (!rows[r][num] && !cols[c][num] && !boxes[box_idx][num]) {
// Place the number.
board[r][c] = (char) (num + '0');
rows[r][num] = true;
cols[c][num] = true;
boxes[box_idx][num] = true;
// Recurse to solve for the rest of the board.
if (backtrack(board, next_r, next_c, rows, cols, boxes)) {
return true;
}
// Backtrack if the placement did not lead to a solution.
boxes[box_idx][num] = false;
cols[c][num] = false;
rows[r][num] = false;
board[r][c] = '.';
}
}
// If no number works, trigger backtracking by returning false.
return false;
}
}
Sudoku Solver in C++
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
// Tracking arrays for used numbers in rows, columns, and 3x3 boxes.
bool rows[9][10] = {false};
bool cols[9][10] = {false};
bool boxes[9][10] = {false};
// Pre-fill the tracking arrays based on the initial board state.
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] != '.') {
int num = board[i][j] - '0';
rows[i][num] = true;
cols[j][num] = true;
boxes[(i / 3) * 3 + j / 3][num] = true;
}
}
}
// Start backtracking from the top-left cell.
backtrack(board, 0, 0, rows, cols, boxes);
}
private:
bool backtrack(vector<vector<char>>& board, int r, int c,
bool rows[9][10], bool cols[9][10], bool boxes[9][10]) {
// If we've processed all rows, the board is solved.
if (r == 9) {
return true;
}
// Calculate coordinates for the next cell.
int next_r = (c == 8) ? r + 1 : r;
int next_c = (c == 8) ? 0 : c + 1;
// If the current cell is already filled, move to the next.
if (board[r][c] != '.') {
return backtrack(board, next_r, next_c, rows, cols, boxes);
}
// Try placing digits 1-9 in the empty cell.
for (int num = 1; num <= 9; ++num) {
int box_idx = (r / 3) * 3 + c / 3;
// Check if the number is valid for the current cell.
if (!rows[r][num] && !cols[c][num] && !boxes[box_idx][num]) {
// Place the number.
board[r][c] = num + '0';
rows[r][num] = true;
cols[c][num] = true;
boxes[box_idx][num] = true;
// Recurse to the next cell.
if (backtrack(board, next_r, next_c, rows, cols, boxes)) {
return true; // Solution found.
}
// If recursion fails, backtrack: undo the placement.
boxes[box_idx][num] = false;
cols[c][num] = false;
rows[r][num] = false;
board[r][c] = '.';
}
}
// If no number from 1-9 works, return false to trigger backtracking.
return false;
}
};
Sudoku Solver in TypeScript
/**
Do not return anything, modify board in-place instead.
*/
function solveSudoku(board: string[][]): void {
// Tracking arrays for used numbers in rows, columns, and boxes.
const rows: boolean[][] = Array(9).fill(0).map(() => Array(10).fill(false));
const cols: boolean[][] = Array(9).fill(0).map(() => Array(10).fill(false));
const boxes: boolean[][] = Array(9).fill(0).map(() => Array(10).fill(false));
// Populate tracking arrays based on the initial board.
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] !== '.') {
const num = parseInt(board[r][c]);
rows[r][num] = true;
cols[c][num] = true;
boxes[Math.floor(r / 3) * 3 + Math.floor(c / 3)][num] = true;
}
}
}
function backtrack(r: number, c: number): boolean {
// Base case: If we've processed all rows, a solution is found.
if (r === 9) {
return true;
}
// Calculate the coordinates of the next cell to visit.
const [nextR, nextC] = c === 8 ? [r + 1, 0] : [r, c + 1];
// If the current cell is already filled, move to the next.
if (board[r][c] !== '.') {
return backtrack(nextR, nextC);
}
// Try placing digits 1-9 in the empty cell.
for (let num = 1; num <= 9; num++) {
const boxIdx = Math.floor(r / 3) * 3 + Math.floor(c / 3);
// Check if placing the number is valid.
if (!rows[r][num] && !cols[c][num] && !boxes[boxIdx][num]) {
// Place the number.
board[r][c] = String(num);
rows[r][num] = true;
cols[c][num] = true;
boxes[boxIdx][num] = true;
// Recurse to the next cell.
if (backtrack(nextR, nextC)) {
return true; // Solution found.
}
// Backtrack if the recursive call fails.
boxes[boxIdx][num] = false;
cols[c][num] = false;
rows[r][num] = false;
board[r][c] = '.';
}
}
// If no number worked, trigger backtracking.
return false;
}
// Start the backtracking process from cell (0, 0).
backtrack(0, 0);
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.