SDE & MLE Prep

36. Valid Sudoku

Problem

Given a partially filled 9×9 Sudoku board (digits '1'–'9' and '.' for empty), decide whether the filled cells are valid so far: no digit repeats within a row, a column, or any of the nine 3×3 boxes. The board doesn't have to be solvable.

Example: a standard puzzle with no repeats → true; the same board with two 8s in one 3×3 box → false

Keep a set for each row, column and 3×3 box. Box index = (r // 3) * 3 + c // 3. Any repeat → invalid.

Complexity: O(81) = O(1).

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        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):
                v = board[r][c]
                if v == ".":
                    continue
                b = (r // 3) * 3 + c // 3
                if v in rows[r] or v in cols[c] or v in boxes[b]:
                    return False
                rows[r].add(v); cols[c].add(v); boxes[b].add(v)
        return True