Skip to main content

Verify Sudoku Board

Determine whether a 9Γ—9 Sudoku board is valid.

Example banner

A board is valid if:

  • Each row contains no duplicate digits 1–9
  • Each column contains no duplicates
  • Each 3Γ—3 subgrid contains no duplicates

Empty cells are represented by ".".

Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
...
]

Output: true
export function isValidSudoku(board: string[][]): boolean {
const rows = new Array(9).fill(null).map(() => new Set());
const cols = new Array(9).fill(null).map(() => new Set());
const boxes = new Array(9).fill(null).map(() => new Set());

for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const val = board[r][c];
if (val === ".") continue;

const boxIndex = Math.floor(r / 3) * 3 + Math.floor(c / 3);

if (rows[r].has(val) || cols[c].has(val) || boxes[boxIndex].has(val)) {
return false;
}

rows[r].add(val);
cols[c].add(val);
boxes[boxIndex].add(val);
}
}

return true;
}