36. Valid Sudoku ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Hash Table
, Matrix
Determine if a 9 x 9 Sudoku board is valid. A board is valid if:
Each row contains the digits 1-9
without repetition.
Each column contains the digits 1-9
without repetition.
Each of the nine 3 x 3 sub-boxes contains the digits 1-9
without repetition.
๐ Notes:
Only the filled cells need to be validated.
A valid board does not necessarily need to be solvable.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
Explanation: The same as Example 1, except there are two 8
s in the top left 3 x 3 sub-box.
board.length == 9
board[i].length == 9
board[i][j]
is a digit 1-9
or '.'
.
To solve the problem, we need to validate:
Each row.
Each column.
Each 3x3 sub-box.
We can use sets to track numbers in each row, column, and sub-box while iterating through the board.
Tracking Validity:
Use a set to store unique strings for each row, column, and 3x3 box.
For example:
"row0-5"
means '5' exists in row 0.
"col1-3"
means '3' exists in column 1.
"box0-0-7"
means '7' exists in the top-left box.
Validation:
Traverse the entire board.
Skip empty cells (denoted by .
).
Check if adding the current number to the set violates any rule.
Result:
If all checks pass, return true
.
Otherwise, return false
.
O(81):
We traverse each cell in the 9x9 board once.
Checking or inserting into a set takes O(1) on average.
O(81):
The set can store up to 81 entries in the worst case.
You can find the full solution here.