codejump
MediumPro challengePythonJavaScriptTypeScript

Matrix — Valid Sudoku

AlgorithmsMatrixHash Set

solve(board) — board is a 9×9 grid of strings: "1"–"9" for a filled cell and
"." for an empty one. Return true when the filled cells break no Sudoku rule:

  • each row holds no digit twice;
  • each column holds no digit twice;
  • each of the nine 3×3 boxes holds no digit twice.

You are *not* asked to solve the puzzle or to check it can be completed — only that what
is on the board is consistent. Do it in a single pass over the 81 cells with one set per
row, per column and per box. The box of cell (r, c) is floor(r / 3) * 3 + floor(c / 3).

Examples

solve(board with 5 3 . . 7 . . . . on the first row …)  → true
solve(same board, but the top-left cell is "8")         → false   // 8 repeats in column 0 and in the box

Sample tests

Test #1Valid partial board
Input: [[["5","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"]]]
Output: true
Test #28 repeats in a column and a box
Input: [[["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"]]]
Output: false
Test #3Empty board
Input: [[[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".",".","."]]]
Output: true