Categories
interview

Valid Sudoku

A valid Sudoku is a 9×9 grid puzzle where each row, column, and 3×3 subgrid contains the numbers 1 to 9 exactly once. Here is an example of a valid Sudoku:

5 3 4 | 6 7 8 | 9 1 2
6 7 2 | 1 9 5 | 3 4 8
1 9 8 | 3 4 2 | 5 6 7
---------------------
8 5 9 | 7 6 1 | 4 2 3
4 2 6 | 8 5 3 | 7 9 1
7 1 3 | 9 2 4 | 8 5 6
---------------------
9 6 1 | 5 3 7 | 2 8 4
2 8 7 | 4 1 9 | 6 3 5
3 4 5 | 2 8 6 | 1 7 9
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
  if (!board) {
    return false;
  }
  const rowArr = [...Array(9)].map(x => new Object());
  const colArr = [...Array(9)].map(x => new Object());
  const boxObj = {};
  for (let i = 0; i < 9; i++) {
    let boxRow = 3 * Math.floor(i / 3) + '.';
    for (let j = 0; j < 9; j++) {
      let c = board[i][j];
      if (c !== '.') {
        if (c in rowArr[i]) {
          return false;
        } else {
          rowArr[i][c] = true;
        }
        if (c in colArr[j]) {
          return false;
        } else {
          colArr[j][c] = true;
        }
        const boxKey = boxRow + (3 * Math.floor(j / 3));
        if (!(boxKey in boxObj)) {
          boxObj[boxKey] = {};
        }
        if (c in boxObj[boxKey]) {
          return false;
        } else {
          boxObj[boxKey][c] = true;
        }
      }
    }
  }
  return true;
}

/**
 * @param {character[][]} board
 * @return {boolean}
 */
// var isValidSudoku = function(board) {
//     if (!board) {
//         return false;
//     }
//     for (let i = 0; i < board.length; i++) {
//       for (let j = 0; j < board[0].length; j++) { 
//           const c = board[i][j];
//           if ( c!== '.' && !valid(c, i , j, board)) {
//             return false;
//           }
//       }
//     }
//     return true;
// };

// var valid = function(c, i, j, board) {
//         const rowStart = 3 * Math.floor(i / 3);
//         const colStart = 3 * Math.floor(j / 3);
//         for (let k = 0; k < 9; k++) {
//           if ((k !== j && board[i][k] === c) || (k !== i && board[k][j] === c)) {
//             return false;
//           }
//             let row = rowStart + Math.floor(k / 3);
//             let col = colStart + (k % 3);
//             if (!(row === i && col === j) && c === board[row][col]) {
//                     return false;
//             }
//     }
//     return true;
// }

Demo