Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A filled cell belongs to three independent groups: its row, its column, and its 3-by-3 box. The board is invalid exactly when a digit repeats in any one of those groups. We only need to remember digits already encountered, not solve the unfinished puzzle.
Approach
- Maintain a set of seen digits for every row, column, and box.
- Visit every cell, skipping
.because it represents an empty position. - Identify the box from the row and column divided by three, rounding down. Python uses the pair of box coordinates; JavaScript flattens that pair into an index.
- If the digit is present in any of its three sets, return
false. Otherwise, add it to all three sets. - Return
trueafter the full scan. This certifies the current placements only; it does not guarantee a complete Sudoku solution exists.
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = defaultdict(set)
cols = defaultdict(set)
boxes = defaultdict(set)
for i in range(9):
for j in range(9):
x = board[i][j]
if x == ".":
continue
if x in rows[i] or x in cols[j] or x in boxes[(i//3,j//3)]:
return False
rows[i].add(x)
cols[j].add(x)
boxes[(i//3,j//3)].add(x)
return TrueComplexity analysis
The displayed code scans at most 81 cells of the fixed 9-by-9 board. Each filled cell is recorded in three sets, for at most 243 total set entries across 27 sets. Time and auxiliary space are both O(1) under the problem's fixed dimensions.
