DSA AnimatorDSA animations
Valid Sudoku LC #36 Medium Hash Sets
Problem

Determine if a 9×9 Sudoku board is valid. Only filled cells need to be validated: each row, each column, and each of the nine 3×3 boxes must contain the digits 1–9 without repetition. Empty cells are marked '.'.

Example 1
Input: board = (classic valid Sudoku board)
Output: true
Explanation: No duplicate digit in any row, column, or 3×3 box.
Example 2
Input: board = (board with '8' duplicated in column 0)
Output: false
Explanation: '8' appears in both row 0 and row 3 of column 0.
Constraints: board.length == 9  |  board[i].length == 9  |  board[i][j] is a digit '1'–'9' or '.'
Try Examples
Approach
One pass: for each non-empty cell, check row, column, and 3×3 box HashSets
Box index = (r/3)*3 + (c/3). If any duplicate found → invalid. O(1) space (fixed 9×9).
Sudoku Board
Row Status
Column Status
Box Status (row-major)
Variables
r (row)
—
c (col)
—
digit
—
row_valid
—
col_valid
—
box_valid
—
HashSet seen
empty
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init 9 row sets, 9 col sets, 9 box sets (or one combined seen set)
2
For each cell: skip '.'. Compute box = (r/3)*3 + c/3
3
If digit already in row[r], col[c], or box[box] → return false
4
Otherwise add digit to all three sets and continue
5
If all 81 cells pass → return true
Time
O(81) = O(1)
Space
O(81) = O(1)
Why HashSets Work

The board is always exactly 9×9 with at most 81 cells, so both time and space are O(1) — bounded by a constant. Three families of sets (rows, columns, boxes) guarantee that each constraint unit is checked independently. The single-pass scan never backtracks: the moment a duplicate is found in any unit, we immediately return false.

How to solve Valid Sudoku

LeetCode 36 · Medium · Matrix · Pattern: Hash Sets

Why the obvious approach is slow

You could check every row, then every column, then every box, in three separate passes. One pass with sets for all three is cleaner.

The key idea

Keep 9 sets for the rows, 9 for the columns, and 9 for the boxes. The box index of a cell is row divided by 3, times 3, plus column divided by 3. For each filled cell, if its digit is already in its row, column or box set, the board is invalid. Otherwise add the digit to all three sets.

Remember

One pass, 27 sets, three checks per cell. Box index equals row over 3, times 3, plus column over 3.

Run the animation above on your own input, or watch the 1:42 video explanation of Valid Sudoku with a dry run and Java code.

More Matrix problems