LeetCode 36: Valid Sudoku — Python Solution

Solve LeetCode 36: Valid Sudoku in Python with a row-column-box sets approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicMatrix
Reusable patternrow-column-box sets
ComplexityO(1) time and O(1) space for a fixed 9×9 board

What the problem is testing

Track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board.

Algorithm

  1. Track seen digits independently for each row, column, and 3×3 box; any duplicate violates the board.
  2. Maintain this invariant: Each tracking set contains exactly the nonempty digits processed in its region.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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 True

Why this is correct

The proof follows the maintained state: Each tracking set contains exactly the nonempty digits processed in its region. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(1) time and O(1) space for a fixed 9×9 board. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Ignore empty cells; the board need not be solvable to be valid.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 76. Minimum Window Substring · Next: 54. Spiral Matrix