LeetCode 36: Valid Sudoku is a Medium matrix problem. This Python walkthrough develops a row-column-box sets solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Matrix |
| Reusable pattern | row-column-box sets |
| Complexity | O(1) time and O(1) space for a fixed 9×9 board |
Recognizing the pattern
Matrix problems become manageable when row, column, layer, or neighbor boundaries are explicit rather than inferred inside nested loops.
For this problem specifically, track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board. The invariant worth writing beside the code is: Each tracking set contains exactly the nonempty digits processed in its region.
Step-by-step algorithm
- Identify the input state consumed by
isValidSudoku(board)and initialize the data required by the row-column-box sets pattern. - Track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board.
- After each update, verify the page’s central invariant: Each tracking set contains exactly the nonempty digits processed in its region.
- Finish only after the boundary behavior is covered: Ignore empty cells; the board need not be solvable to be valid.
Python solution
class Solution:
def isValidSudoku(self, board):
rows = [set() for _ in range(9)]; cols = [set() for _ in range(9)]; boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
value = board[r][c]
if value == ".": continue
box = (r // 3) * 3 + c // 3
if value in rows[r] or value in cols[c] or value in boxes[box]: return False
rows[r].add(value); cols[c].add(value); boxes[box].add(value)
return TrueReading the implementation
The main entry point is isValidSudoku(board). The named working state includes rows, value, box; those variables make the row-column-box sets state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board. Each update records the current item without invalidating earlier decisions; consequently, each tracking set contains exactly the nonempty digits processed in its region.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(1) time and O(1) space for a fixed 9×9 board. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An auxiliary matrix can make reads and writes independent, while marker or boundary techniques trade that clarity for lower space use. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
board=[["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"]]; assert Solution().isValidSudoku(board)Common mistakes and edge cases
- Problem-specific boundary: Ignore empty cells; the board need not be solvable to be valid.
- Pattern-level pitfall: Rectangular inputs, one-row layers, and one-column layers expose off-by-one errors that square examples often hide.
- Invariant check: after every update, confirm that each tracking set contains exactly the nonempty digits processed in its region.
Interview review checklist
- Explain why row-column-box sets matches the structure of this input.
- State the invariant in one sentence before tracing code: Each tracking set contains exactly the nonempty digits processed in its region.
- Derive O(1) time and O(1) space for a fixed 9×9 board from how many times each element or state is visited.
- Test the boundary explicitly: Ignore empty cells; the board need not be solvable to be valid.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 76. Minimum Window Substring · Next: 54. Spiral Matrix