Valid Sudoku [Solution]
Here’s a Python implementation of the is_valid_sudoku
function to determine
whether a Sudoku board is valid:
from typing import List
def is_valid_sudoku(board: List[List[str]]) -> bool:
"""
Determine if a Sudoku board is valid.
Parameters:
- board: 2D list representing the Sudoku board.
Returns:
- bool: True if the board is valid, False otherwise.
"""
# Helper function to check if a list of values contains duplicates (excluding '.')
def has_duplicates(nums: List[str]) -> bool:
seen = set()
for num in nums:
if num != '.':
if num in seen:
return True
seen.add(num)
return False
# Check rows and columns for duplicates
for i in range(9):
row = board[i]
column = [board[j][i] for j in range(9)]
if has_duplicates(row) or has_duplicates(column):
return False
# Check 3x3 sub-boxes for duplicates
for i in range(0, 9, 3):
for j in range(0, 9, 3):
sub_box = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
if has_duplicates(sub_box):
return False
return True
# Example usage:
board1 = [
["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"]
]
result1 = is_valid_sudoku(board1)
print(result1) # Output: True
board2 = [
["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"]
]
result2 = is_valid_sudoku(board2)
print(result2) # Output: False
This solution checks each row, column, and 3x3 sub-box for duplicates according to the rules of Sudoku.
Time Complexity:
The time complexity is O(1
) since the board is always a fixed size (9x9).
Space Complexity:
The space complexity is O(1
) because the variables’ sizes are within the board size, which is fixed at 9x9.