Given a 9 × 9 Sudoku board, determine whether it is valid. A board is considered valid if all of the following conditions hold (considering only the filled cells):
Each row contains the digits 1–9 at most once.
Each column contains the digits 1–9 at most once.
Each of the nine 3 × 3 sub-boxes contains the digits 1–9 at most once.
You do not need to check whether the Sudoku is solvable; only whether the current filled entries obey these rules.
Note: A partially filled Sudoku board can be valid even if it is not necessarily solvable. You only need to verify that the filled cells adhere to the given rules.
Constraints:
board.length
board[i].length
board[i][j] is a digit or ..
The intuition behind this solution is simple: instead of trying to solve the Sudoku or perform any form of search or backtracking, we treat the board as a constraint-checking problem. As we scan the board once, cell by cell, we ensure that every filled digit obeys the Sudoku rules, which require no repetition in its row, column, or 3×3 sub-box. To do this efficiently, we maintain three arrays of hash sets:
rows[9]: Tracks digits seen in each row.
cols[9]: Tracks digits seen in each column.
boxes[9]: Tracks digits seen in each 3×3 sub-box.
Each set keeps track of the digits that have already appeared in that specific region. For every filled cell, if the digit is already in its row, ...
Given a 9 × 9 Sudoku board, determine whether it is valid. A board is considered valid if all of the following conditions hold (considering only the filled cells):
Each row contains the digits 1–9 at most once.
Each column contains the digits 1–9 at most once.
Each of the nine 3 × 3 sub-boxes contains the digits 1–9 at most once.
You do not need to check whether the Sudoku is solvable; only whether the current filled entries obey these rules.
Note: A partially filled Sudoku board can be valid even if it is not necessarily solvable. You only need to verify that the filled cells adhere to the given rules.
Constraints:
board.length
board[i].length
board[i][j] is a digit or ..
The intuition behind this solution is simple: instead of trying to solve the Sudoku or perform any form of search or backtracking, we treat the board as a constraint-checking problem. As we scan the board once, cell by cell, we ensure that every filled digit obeys the Sudoku rules, which require no repetition in its row, column, or 3×3 sub-box. To do this efficiently, we maintain three arrays of hash sets:
rows[9]: Tracks digits seen in each row.
cols[9]: Tracks digits seen in each column.
boxes[9]: Tracks digits seen in each 3×3 sub-box.
Each set keeps track of the digits that have already appeared in that specific region. For every filled cell, if the digit is already in its row, ...