Determine whether a partially filled 9×9 Sudoku board is valid: no digit 1–9 may repeat within a row, a column or a 3×3 box. Empty cells are '.'. The board need not be solvable.
Visit each filled cell once and check three sets at the same time: its row, its column and its box (index ⌊r/3⌋·3 + ⌊c/3⌋).
1function isValidSudoku(board: string[][]): boolean {2const rows = Array.from({ length: 9 }, () => new Set<string>());3const cols = Array.from({ length: 9 }, () => new Set<string>());4const boxes = Array.from({ length: 9 }, () => new Set<string>());5for (let r = 0; r < 9; r++)6for (let c = 0; c < 9; c++) {7const d = board[r][c];8if (d === ".") continue;9const b = Math.floor(r / 3) * 3 + Math.floor(c / 3);10if (rows[r].has(d) || cols[c].has(d) || boxes[b].has(d)) return false;11rows[r].add(d); cols[c].add(d); boxes[b].add(d);12}13return true;14}
| 8 | 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 |
27 empty sets: 9 rows, 9 columns, 9 boxes.
Space: play/pause · ←/→: step