Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created August 30, 2025 22:36
Show Gist options
  • Save Ifihan/04c9e9fd0091b4959708f93e3902a203 to your computer and use it in GitHub Desktop.
Save Ifihan/04c9e9fd0091b4959708f93e3902a203 to your computer and use it in GitHub Desktop.
Valid Sudoku

Question

Approach

I scan the 9×9 board once and validate three constraints simultaneously. I keep three collections: one for rows, one for columns, and one for the 3×3 sub-boxes. For each filled cell (r, c) with digit d, I check if d already exists in row[r], col[c], or box[r//3][c//3]. If it does, the board is invalid; otherwise I insert d into all three.

Implementation

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(3)] for _ in range(3)]

        for r in range(9):
            for c in range(9):
                ch = board[r][c]
                if ch == '.':
                    continue
                if ch in rows[r] or ch in cols[c] or ch in boxes[r//3][c//3]:
                    return False
                rows[r].add(ch)
                cols[c].add(ch)
                boxes[r//3][c//3].add(ch)
        return True

Complexities

  • Time: O(1)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment