Skip to content
GKgkml.dev
← Problem set
#36MediumArrays & hashing

Valid Sudoku

The tell: Constraint checking across three overlapping groupings of the same cells.

How you get there

  1. 1Rows, columns and 3×3 boxes are three independent uniqueness constraints.
  2. 2Index the box as (r // 3, c // 3), which is the only non-obvious part.
  3. 3One pass over 81 cells updates all three sets, so validity falls out in constant time.

Solution

Python
from collections import defaultdict

def is_valid_sudoku(board: list[list[str]]) -> bool:
    rows = defaultdict(set)
    cols = defaultdict(set)
    boxes = defaultdict(set)

    for r in range(9):
        for c in range(9):
            value = board[r][c]
            if value == ".":
                continue
            box = (r // 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
Time
O(1) — the board is fixed at 9×9
Space
O(1)

What goes wrong

Computing the box index as r // 3 + c // 3 collides distinct boxes; it must be a tuple or r // 3 * 3 + c // 3.