CodeArchon

mediumArrays & HashingAppleAmazonUber

Checkerboard Audit

A puzzle magazine checks a partially filled Sudoku board against the three house rules before publishing.

Determine whether a 9 × 9 Sudoku board is valid. Only filled cells need to be validated. A board is valid if every row, every column, and every 3 × 3 sub-box contain each digit 1–9 at most once.

Choose approach

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
1/62
Narrationstep 1 of 62

Three guards: one per row, one per column, one per 3×3 box. We walk every filled cell and reject any digit already seen in any of its three groups.

1def is_valid_board(grid: list[list[str]]) -> bool:
2 rows = [set() for _ in range(9)]
3 cols = [set() for _ in range(9)]
4 boxes = [set() for _ in range(9)]
5 for r in range(9):
6 for c in range(9):
7 v = grid[r][c]
8 if v == ".":
9 continue
10 b = (r // 3) * 3 + (c // 3)
11 if v in rows[r] or v in cols[c] or v in boxes[b]:
12 return False
13 rows[r].add(v); cols[c].add(v); boxes[b].add(v)
14 return True
Variables
r=—
c=—
box=—

How to think about it

  1. Three independent constraints: row, column, 3×3 box.
  2. Precompute the box index for a cell: `(r/3)*3 + (c/3)`.
  3. Maintain nine sets for each axis.
  4. For every filled cell, reject if the digit is already in any set; otherwise insert.
  5. Pass through all 81 cells — total work is constant.

Edge cases to catch in interview

  • An entirely empty board is valid (nothing to check).
  • Duplicates may appear within a single row/column/box — any of the three triggers rejection.
  • '.' cells are placeholders and are skipped.

Examples

Example 1true
{"grid":[["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"]]}

Puzzle respects every row/col/box.

Example 2false
{"grid":[["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"]]}

Two 8s share the top-left 3×3 box.

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed