InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Valid Sudoku

medium Original ↗ 00:00

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 8False 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 board size is fixed at 9×9, so the work is technically O(1). The point of the exercise is to validate it in a single 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug