Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 30, 2025 17:23
Show Gist options
  • Save tatsuyax25/de51eec85fd381a34cfbcff7f3159ce3 to your computer and use it in GitHub Desktop.
Save tatsuyax25/de51eec85fd381a34cfbcff7f3159ce3 to your computer and use it in GitHub Desktop.
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the
/**
* Validates a partially filled 9x9 Sudoku board.
* Only filled cells are checked for rule violations.
*
* @param {character[][]} board - 2D array representing the Sudoku board
* @return {boolean} - true if the board is valid, false otherwise
*/
var isValidSudoku = function(board) {
// Set to track seen digits in rows, columns, and sub-boxes
const seen = new Set();
// Iterate over each cell in the 9x9 grid
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
const value = board[row][col];
// Skip empty cells
if (value === '.') continue;
// Encode the presence of the digit in row, column, and sub-box
const rowKey = `row-${row}-${value}`;
const colKey = `col-${col}-${value}`;
const boxKey = `box-${Math.floor(row / 3)}-${Math.floor(col / 3)}-${value}`;
// If any of these keys already exist, it's a duplicate → invalid
if (seen.has(rowKey) || seen.has(colKey) || seen.has(boxKey)) {
return false;
}
// Otherwise, record the digit's presence
seen.add(rowKey);
seen.add(colKey);
seen.add(boxKey);
}
}
// No violations found
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment