PracticeNeetCode ↗LeetCode ↗
Determine if a 9×9 Sudoku board is valid: each row, each column, and each of the nine 3×3 sub-boxes must contain the digits 1–9 without repetition. Only the filled cells need checking — the board doesn't need to be solvable.
(r // 3) * 3 + c // 3 maps any (row, col) to one of nine box ids, 0–8 — worth memorizing.(r, c), skip it if the value is ".".b = (r // 3) * 3 + c // 3.rows[r], cols[c], or boxes[b], return False; otherwise add it to all three.True.Time: O(1) — the board is a fixed 81 cells — Space: O(1)
def isValidSudoku(board: list[list[str]]) -> bool:
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
val = board[r][c]
if val == ".":
continue
b = (r // 3) * 3 + c // 3
if val in rows[r] or val in cols[c] or val in boxes[b]:
return False
rows[r].add(val)
cols[c].add(val)
boxes[b].add(val)
return TrueHow the solution above works, piece by piece.
rows, cols and boxes, each remembering the digits seen in that row, column or box.'.' means empty and is skipped.b = (r // 3) * 3 + c // 3 numbers the 3×3 boxes 0–8: r // 3 picks the band of rows, c // 3 the band of columns.False.An example board where row 0 contains two 5s:
rows[0], so the board is invalid.