Notes

Personal notes on various topics

View on GitHub

Intuition

To check if a Sudoku board is valid, we need to ensure that each digit appears only once in every row, column, and 3x3 sub-box. Using bitmasks allows us to efficiently track the presence of digits in each row, column, and box.

Approach

Complexity

Code

from typing import List

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        N = 9

        rows = [0] * N
        cols = [0] * N
        boxs = [0] * N

        for r in range(N):
            for c in range(N):
                if board[r][c] == ".":
                    continue

                pos = int(board[r][c]) - 1

                if rows[r] & (1 << pos):
                    return False
                rows[r] |= 1 << pos

                if cols[c] & (1 << pos):
                    return False
                cols[c] |= 1 << pos

                idx = (r // 3) * 3 + (c // 3)
                if boxs[idx] & (1 << pos):
                    return False
                boxs[idx] |= 1 << pos

        return True

Back to Problem Statement