CodingNodes / Arrays & Hashing / Valid Sudoku System design Space play · ←→ step · R restart

Problem

A 9 × 9 Sudoku board is given as a grid of characters: a digit from "1" to "9", or "." for an empty cell. Decide whether the digits already placed follow the Sudoku rules:

  • no digit repeats within a row,
  • no digit repeats within a column,
  • no digit repeats within any of the nine 3 × 3 boxes (the board is cut into 3 × 3 blocks).

Only the filled cells are checked. The board does not need to be solvable; return true when no rule is broken and false otherwise.

Constraints

  • board.length == 9 and board[i].length == 9
  • board[i][j] is a digit '1'–'9' or '.'

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(1)

Time: The board always has 81 cells and each is handled with constant-time set operations.

Space: There are 27 sets, and together they never hold more than 81 digits, a fixed size.

Scan the cells once. Keep a set of seen digits for each of the 9 rows, 9 columns and 9 boxes. The box of cell (r, c) is (r / 3) × 3 + c / 3. If a digit is already in any of its three sets the board is invalid; otherwise add it to all three.