36. Valid Sudoku
MediumSolutions 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 problem asks us to determine if a 9x9 Sudoku board is valid. A board is valid if the numbers present satisfy three conditions:
- No repeated numbers in any row.
Solution
Valid Sudoku in Python
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# Initialize data structures to track seen numbers.
# Using sets for efficient O(1) average time complexity for add/check.
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
# Iterate through each cell of the 9x9 board.
for i in range(9):
for j in range(9):
char = board[i][j]
# If the cell is empty, skip it.
if char == '.':
continue
# Calculate the index for the 3x3 sub-box.
box_index = (i // 3) * 3 + (j // 3)
# Check for duplicates in the current row, column, and 3x3 box.
if char in rows[i] or char in cols[j] or char in boxes[box_index]:
return False # Found a duplicate.
# Mark the number as seen for the current row, column, and box.
rows[i].add(char)
cols[j].add(char)
boxes[box_index].add(char)
# If no duplicates were found, the board is valid.
return True
Valid Sudoku in Java
class Solution {
public boolean isValidSudoku(char[][] board) {
// Use boolean arrays to track seen numbers.
// rows[i][num] is true if number `num+1` is in row `i`.
// cols[j][num] is true if number `num+1` is in column `j`.
// boxes[k][num] is true if number `num+1` is in box `k`.
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] boxes = new boolean[9][9];
// Iterate through each cell of the 9x9 board.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// If the cell is empty, skip it.
if (board[i][j] == '.') {
continue;
}
// Convert character digit to an integer index (0-8).
int num = board[i][j] - '1';
// Calculate the index for the 3x3 sub-box.
int boxIndex = (i / 3) * 3 + (j / 3);
// Check for duplicates in the current row, column, and 3x3 box.
if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
return false; // Found a duplicate.
}
// Mark the number as seen for the current row, column, and box.
rows[i][num] = true;
cols[j][num] = true;
boxes[boxIndex][num] = true;
}
}
// If no duplicates were found after checking all cells, the board is valid.
return true;
}
}
Valid Sudoku in C++
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
// Use boolean arrays to keep track of seen numbers.
// rows[i][num] is true if number `num+1` is in row `i`.
// cols[j][num] is true if number `num+1` is in column `j`.
// boxes[k][num] is true if number `num+1` is in box `k`.
bool rows[9][9] = {false};
bool cols[9][9] = {false};
bool boxes[9][9] = {false};
// Iterate through each cell of the 9x9 board.
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
// If the cell is empty, skip it.
if (board[i][j] == '.') {
continue;
}
// Convert character digit to an integer index (0-8).
int num = board[i][j] - '1';
// Calculate the index for the 3x3 sub-box.
int box_index = (i / 3) * 3 + (j / 3);
// Check for duplicates in the current row, column, and 3x3 box.
if (rows[i][num] || cols[j][num] || boxes[box_index][num]) {
return false; // Found a duplicate.
}
// Mark the number as seen for the current row, column, and box.
rows[i][num] = true;
cols[j][num] = true;
boxes[box_index][num] = true;
}
}
// If no duplicates were found after checking all cells, the board is valid.
return true;
}
};
Valid Sudoku in TypeScript
function isValidSudoku(board: string[][]): boolean {
// Use arrays of sets to track seen numbers.
const rows: Set<string>[] = Array.from({ length: 9 }, () => new Set());
const cols: Set<string>[] = Array.from({ length: 9 }, () => new Set());
const boxes: Set<string>[] = Array.from({ length: 9 }, () => new Set());
// Iterate through each cell of the 9x9 board.
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
const char = board[i][j];
// If the cell is empty, skip it.
if (char === '.') {
continue;
}
// Calculate the index for the 3x3 sub-box.
const boxIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3);
// Check for duplicates in the current row, column, and 3x3 box.
if (rows[i].has(char) || cols[j].has(char) || boxes[boxIndex].has(char)) {
return false; // Found a duplicate.
}
// Mark the number as seen for the current row, column, and box.
rows[i].add(char);
cols[j].add(char);
boxes[boxIndex].add(char);
}
}
// If no duplicates were found, the board is valid.
return true;
}
More Medium 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.