Given a fully or partially attempted 9x9 Sudoku board, determine if it is a valid solution.
MediumDetermine whether a partly filled 9 x 9 Sudoku board is valid so far. Only the filled cells need to follow the rules:
- Each row contains the digits
1to9at most once. - Each column contains the digits
1to9at most once. - Each of the nine
3 x 3boxes contains the digits1to9at most once.
Empty cells are written as ".". A valid board doesn't have to be solvable: you're only checking the digits already on it.
Example 1
Input: board = . . . . . . 7 . . . . 6 . 8 . . 2 3 7 . . 1 . 3 . 5 6 . 3 4 . . 7 . . . 5 . . . . 1 . 3 4 8 9 . 2 . 4 5 . . 3 . . 6 . 8 . . 2 . . . 9 1 2 . 4 . . . 2 . . . 6 . . Output: true
No digit repeats in any row, column or box.
Example 2
Input: board = . . . . 9 . . . . . . . . . . . . . . . . . . . . . . . 7 . . 2 . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Output: false
The fourth row has two 7s.
Constraints
boardhas 9 rows and 9 columns.- Each cell is a digit from
1to9or".".
Approach
A digit breaks the rules if it has already appeared in the same row, the same column or the same box. Checking that by rescanning the row, column and box for every cell works, but it repeats a lot of effort.
Instead, make one pass over the board and remember what you've seen. Keep nine sets for the rows, nine for the columns and nine for the boxes. Cell (r, c) belongs to row r, column c and box (r // 3) * 3 + c // 3, which numbers the boxes left to right, top to bottom. For each filled cell, check its digit against its three sets. If it's already in any of them, the board is invalid. Otherwise add it to all three.
The Java and C++ solutions use 9 x 9 boolean arrays instead of sets, indexed by unit and digit. It's the same idea with less overhead.
Steps
- Create a set of seen digits for each row, column and box.
- Visit every cell, skipping
".". - Compute the cell's box index as
(r // 3) * 3 + c // 3. - If the digit is already in the row's, column's or box's set, return
false. - Otherwise add it to all three sets. Return
trueafter the last cell.
Complexity
- Time:
O(1). The board always has 81 cells. For ann x nboard, it'sO(n^2). - Space:
O(1). At most 81 digits are stored across all the sets.
Common mistakes
- Computing the box index as
r // 3 + c // 3, which gives the same index to different boxes. - Treating
"."as a value, so two empty cells in a row look like a repeat. - Trying to solve the puzzle. A board can be valid by these rules and still have no solution.
Interview experiences
1 sharedRelated courses



