InterviewPrepKit

Home / Coding / Arrays & Hashing

Valid Sudoku

medium Original β†—
Solving tips
  • Recognize 27 simultaneous 'no duplicates in a group' constraints (9 rows, 9 columns, 9 boxes); each is an O(1) hash-set membership check.
  • Visit each cell once, skip '.', and fail the moment a digit is already present in its row, column, or box set; O(n^2) over the board (constant for 9x9).
  • The box index flattens to (r // 3) * 3 + c // 3; a bitmask int per group can replace each set to minimize memory.
  • Pitfall: don't forget the box check (row/col-only misses box violations), skip empty cells, and get the box formula's coordinate multiplication right.

Problem

You’re given a 9Γ—9 Sudoku board where each cell holds a digit character "1"–"9" or "." for empty. Decide whether the board’s current filled cells are consistent with the rules:

  1. No digit repeats within a row.
  2. No digit repeats within a column.
  3. No digit repeats within any of the nine 3Γ—3 sub-boxes.

Only validate what’s filled in β€” the board does not need to be solvable or complete; empty cells are ignored.

Examples

Example 1:

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

β†’ True β€” no row, column, or box has a repeated digit.

Example 2: the same board with the top-left 5 changed to 8 β†’ False Column 0 now holds two 8s (rows 0 and 3), and the top-left 3Γ—3 box also gets two 8s.

Example 3: a board whose row 4 is 1 . . . 1 . . . . (all else empty) β†’ False β€” duplicate 1 in one row.

Constraints

  • The board is always 9Γ—9; cells are "1"–"9" or ".".

The input size is fixed, so everything is technically O(1) β€” the exercise is doing it in one pass with clean bookkeeping instead of 27 separate scans.

Think about it first

Hint 1 Checking one row for duplicates is easy. How many independent "no duplicates" groups does the whole board have?
Hint 2 Every cell belongs to exactly one row, one column, and one box. Could you visit each cell once and record its digit in all three of its groups, failing fast on a repeat?
Hint 3 Keep 9 sets for rows, 9 for columns, 9 for boxes. A cell (r, c) lands in box `(r // 3) * 3 + c // 3`. If the digit is already in any of the three sets β†’ invalid; otherwise add it to all three.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.