class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# Validate Rows
for i in range(9):
s = set()
for j in range(9):
item = board[i][j]
if item in s:
return False
elif item != '.':
s.add(item)
# Validate Cols
for i in range(9):
s = set()
for j in range(9):
item = board[j][i]
if item in s:
return False
elif item != '.':
s.add(item)
# Validate Boxes
starts = [(0, 0), (0, 3), (0, 6),
(3, 0), (3, 3), (3, 6),
(6, 0), (6, 3), (6, 6)]
for i, j in starts:
s = set()
for row in range(i, i+3):
for col in range(j, j+3):
item = board[row][col]
if item in s:
return False
elif item != '.':
s.add(item)
return True
# Time Complexity: O(n^2)
# Space Complexity: O(n)
The “Valid Sudoku” problem asks us to determine whether a partially filled 9×9 Sudoku board is valid. A board is valid if:
Empty cells are represented by the character '.'
and should be ignored during validation.
Validating a Sudoku board is a useful exercise in applying set logic, matrix traversal, and multi-dimensional constraints. It frequently appears in coding interviews because it combines pattern checking with efficient scanning of 2D structures.
The problem can be broken down into three separate validations:
false
.
false
If no violations are found in any row, column, or sub-box, the board is valid.
Here's a sample valid board layout:
Each row, column, and 3Ă—3 box in this board has no duplicates (ignoring '.'), so it is valid.
Time Complexity: O(1) – The board is always 9×9, so we iterate over a constant number of cells.
Space Complexity: O(1) – We use fixed-size sets for rows, columns, and boxes, each handling at most 9 digits.
The “Valid Sudoku” problem teaches how to apply multiple constraints across different dimensions of a matrix. By using simple data structures like sets and scanning in a structured way, you can implement an elegant and efficient solution that checks all rules without overcomplication.