Valid Sudoku
Validate a 9×9 board row-wise, column-wise, and across each 3×3 grid. Every check is the same: a Set that flags the first repeat.
The problem
Determine whether a 9×9 Sudoku board is valid. Only the filled cells need to be checked, and they're valid when each row holds the digits 1–9 without repetition, each column does too, and each of the nine 3×3 sub-boxes does as well.
A board can be valid without being solvable — I only have to confirm that what's already placed breaks none of the three rules.
The approach
My idea is to validate the board in three sweeps — first column-wise, then row-wise, and finally by dividing it into 3×3 grids. If any sweep finds a violation I return false; if all three pass, the board is valid.
Every sweep runs the same validation logic: keep a Set, and for each filled cell, if its value is already in the Set then it's a repeat so the board is invalid; otherwise add it and continue. For the 3×3 grids I step `i` and `j` by 3 and hand each block to a helper that runs that same Set check over its nine cells.
The solution
/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
//validate coloumn
for(let i=0;i<board.length;i++){
const set = new Set()
for(let j=0;j < board[0].length;j++) {
if(board[j][i] != "."){
if(set.has(board[j][i])) {
return false
}
else {
set.add(board[j][i])
}
}
}
}
// validate rows
for(let i=0;i<board.length;i++){
const set = new Set()
for(let j=0;j< board[0].length;j++) {
if(board[i][j] != "."){
if(set.has(board[i][j])) {
return false
}
else {
set.add(board[i][j])
}
}
}
}
// validate 3by3 grids
for(let i=0;i<board.length;i+=3) {
for(let j=0;j< board[0].length;j+=3) {
if(!validate3by3Grid(i,j,board)){
return false
}
}
}
return true
};
var validate3by3Grid = function(inn,jnn, board) {
const set = new Set()
for(let i=inn;i<inn+3;i++) {
for(let j=jnn;j<jnn+3;j++){
if(board[i][j] != "."){
if(set.has(board[i][j])) {
return false
}
else {
set.add(board[i][j])
}
}
}
}
return true
}Time O(1)Space O(1)