36. Valid Sudoku
Last updated
Was this helpful?
Last updated
Was this helpful?
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules :
Each row must contain the digits 1-9
without repetition.
Each column must contain the digits 1-9
without repetition.
Each of the nine 3 x 3
sub-boxes of the grid must contain the digits 1-9
without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Example 2:
Constraints:
board.length == 9
board[i].length == 9
board[i][j]
is a digit or '.'
.
Hash Table
We initialize 3*9=27 hash tables (mapping from cell value to count) for 9 row, 9 columns and 9 boxes, and iterate only once over the board. For each cell value (skip if it is an empty cell), if it has already been stored in one of 27 hash tables, we return false. Otherwise, we add 1 to the respective slot. After the loop, return true.
Time complexity:
Space complexity: