Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
The Sudoku board could be partially filled, where empty cells are represented by the character ‘.’.
Input:
board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
To determine if a Sudoku board is valid, we need to check three main conditions:
We’ll use a hash set to keep track of digits we’ve seen so far for each row, column, and sub-box.
public class Solution {
public boolean isValidSudoku(char[][] board) {
// HashSet to keep track of the digits we have seen so far in rows, columns, and sub-boxes
HashSet<String> seen = new HashSet<>();
// We iterate through every cell in the 9x9 grid board
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char current = board[i][j];
// If the current cell contains a digit (1-9)
if (current != '.') {
// Create unique strings for row, column, and sub-box conditions
String rowCheck = current + " in row " + i;
String colCheck = current + " in column " + j;
String boxCheck = current + " in box " + (i / 3) + "-" + (j / 3);
// If any of the strings already exist in the set, it means there is a duplicate
if (!seen.add(rowCheck) || !seen.add(colCheck) || !seen.add(boxCheck)) {
return false;
}
}
}
}
return true;
}
}
Thus, the solution is highly efficient for the given problem, maintaining constant time and space complexities.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?