36. Valid Sudoku 🌐
Difficulty: Medium - Tags: Hash Table, Matrix
Problem Statement 📜
Determine if a 9 x 9 Sudoku board is valid. A board is valid if:
Each row contains the digits
1-9without repetition.Each column contains the digits
1-9without repetition.Each of the nine 3 x 3 sub-boxes contains the digits
1-9without repetition.
📝 Notes:
Only the filled cells need to be validated.
A valid board does not necessarily need to be solvable.
Examples 🌟
🔹 Example 1:

Input:
Output:
🔹 Example 2:
Input:
Output:
Explanation: The same as Example 1, except there are two 8s in the top left 3 x 3 sub-box.
Constraints ⚙️
board.length == 9board[i].length == 9board[i][j]is a digit1-9or'.'.
Solution 💡
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.
Java Solution
Explanation of the Solution
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.
Time Complexity ⏳
O(81):
We traverse each cell in the 9x9 board once.
Checking or inserting into a set takes O(1) on average.
Space Complexity 💾
O(81):
The set can store up to 81 entries in the worst case.
You can find the full solution here.
Last updated
Was this helpful?