Valid Sudoku: the idea to remember.
Check whether the filled cells of a 9 by 9 Sudoku board obey row, column and box uniqueness.
The core insight
Track seen digits separately for each row, column and 3 by 3 box; skip empty cells.
Why it works
A board is valid exactly when no filled digit repeats in any of its three containing units.
The mistake to avoid
A valid partial board need not have a complete solution. Ignore dots rather than treating them as digits.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Track seen digits separately for each row, column and 3 by 3 box; skip empty cells.
public boolean isValidSudoku(char[][] board) {
Set<Character> rowSet = null;
Set<Character> colSet = null;
for (int i = 0; i < 9; i++) {
rowSet = new HashSet<>();
colSet = new HashSet<>();
for (int j = 0; j < 9; j++) {
char r = board[i][j];
char c = board[j][i];
if (r != '.'){
if (rowSet.contains(r)){
return false;
} else {
rowSet.add(r);
}
}
if (c != '.'){
if (colSet.contains(c)){
return false;
} else {
colSet.add(c);
}
}
}
}
for (int i = 0; i < 9; i = i + 3) {
for (int j = 0; j < 9; j = j + 3) {
if (!checkBlock(i, j, board)) {
return false;
}
}
}
return true;
}
public boolean checkBlock(int idxI, int idxJ, char[][] board) {
Set<Character> blockSet = new HashSet<>();
int rows = idxI + 3;
int cols = idxJ + 3;
for (int i = idxI; i < rows; i++) {
for (int j = idxJ; j < cols; j++) {
if (board[i][j] == '.') {
continue;
}
if (blockSet.contains(board[i][j])) {
return false;
}
blockSet.add(board[i][j]);
}
}
return true;
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.