Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1-9
without repetition.1-9
without repetition.3 x 3
sub-boxes of the grid must contain the digits 1-9
without repetition.Note:
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: true
Example 2:
Input: board = [["8","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: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit 1-9
or '.'
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To solve the Sudoku problem by brute force, we check all possible numbers for each empty spot. We fill in each spot one by one, trying every possible digit from 1 to 9, until a valid or invalid solution is found.
Here's how the algorithm would work step-by-step:
def is_valid_sudoku(board):
board_size = 9
def is_valid(row_number, column_number, number):
# Check if the number is already present in the row
for i in range(board_size):
if board[row_number][i] == str(number):
return False
# Check if the number is already present in the column
for i in range(board_size):
if board[i][column_number] == str(number):
return False
# Check if the number is already present in the 3x3 sub-grid
subgrid_row_start = (row_number // 3) * 3
subgrid_col_start = (column_number // 3) * 3
for i in range(3):
for j in range(3):
if board[subgrid_row_start + i][subgrid_col_start + j] == str(number):
return False
return True
def solve_sudoku():
for row_number in range(board_size):
for column_number in range(board_size):
if board[row_number][column_number] == '.':
# Try each number from 1 to 9
for number in range(1, 10):
# Check if the current number is valid
if is_valid(row_number, column_number, number):
board[row_number] = board[row_number][:column_number] + str(number) + board[row_number][column_number+1:]
# Recursively try to solve the rest of the Sudoku
if solve_sudoku():
return True
# If the recursive call fails, backtrack
board[row_number] = board[row_number][:column_number] + '.' + board[row_number][column_number+1:]
# No valid number was found, so we need to backtrack
return False
# If no empty cells are left, the Sudoku is solved
return True
return solve_sudoku()
The goal is to check if a partially filled Sudoku board follows the rules. The efficient method involves checking each row, column, and 3x3 square only once to see if any numbers are repeated within them.
Here's how the algorithm would work step-by-step:
def is_valid_sudoku(board):
board_size = 9
def has_duplicates(elements):
seen = set()
for element in elements:
if element != '.' and element in seen:
return True
seen.add(element)
return False
# Check each row for duplicates
for row in range(board_size):
if has_duplicates(board[row]):
return False
# Check each column for duplicates
for column in range(board_size):
if has_duplicates([board[row][column] for row in range(board_size)]):
return False
# Check each 3x3 sub-box for duplicates
# Ensures each sub-box has unique values
for box_row in range(0, board_size, 3):
for box_column in range(0, board_size, 3):
elements_in_subgrid = [
board[row][column]
for row in range(box_row, box_row + 3)
for column in range(box_column, box_column + 3)
]
if has_duplicates(elements_in_subgrid):
return False
return True
Case | How to Handle |
---|---|
Null or empty board input | The code should check for null or empty board input and return true immediately because an empty board satisfies the Sudoku rules vacuously. |
Board with invalid dimensions (not 9x9) | The code should validate the board dimensions before processing, returning false if it's not a 9x9 matrix. |
Board containing characters other than digits 1-9 or '.' | The code should validate each cell, returning false if it finds a character outside the allowed set (1-9, .). |
All cells are empty ('.') | The solution should correctly handle this case, resulting in a valid Sudoku (return true). |
A single row, column, or box contains duplicate digits | The solution uses sets to detect duplicates within each row, column, and 3x3 sub-box and returns false if found. |
Board with very large numbers if non-character types were incorrectly used | Since the input is characters '1'-'9', the code does not need to handle integer overflow or large numbers. |
Board with maximum allowed number of filled cells but still invalid | The sets used for validation still work correctly to detect duplicates even when a very large number of cells are filled (but the board remains invalid). |
Integer overflow when calculating box index | The box index calculation `(row / 3) * 3 + column / 3` is designed to prevent integer overflow because row, column are in range [0, 8]. |