Skip to content

Conversation

@Athting
Copy link

@Athting Athting commented Oct 4, 2025

Approach: Hashing with Bitsets
We need to check whether a given partially filled Sudoku board is valid (not necessarily solvable).

Rules
Each row must contain unique digits 1–9.
Each column must contain unique digits 1–9.
Each 3×3 subgrid must contain unique digits 1–9.

Implementation idea
Use 3 arrays of bitsets (or hash sets):
row[9] → track used digits in each row.
col[9] → track used digits in each column.
block[9] → track used digits in each 3×3 block.

Traverse the board:
Skip if the cell is '.'.
Convert digit '1'–'9' into index 0–8.
Compute blockIndex = (r / 3) * 3 + (c / 3).
If the digit already exists in the corresponding row, column, or block → invalid.
Otherwise, mark it as used.
If traversal completes with no conflict → board is valid.

Intuition
Think of it as tracking duplicates in three different dimensions simultaneously:
While scanning each cell, we “register” the digit in its row, column, and sub-box.
If a duplicate appears in any of the three, the Sudoku board becomes invalid immediately.
Using bitsets makes this very efficient since checking and setting bits both take O(1) time.

Solution in Code (C++)
class Solution {
public:
bool isValidSudoku(vector<vector>& board) {
bitset<9> Col[9];
bitset<9> Row[9];
bitset<9> Block[9];

    for(int i = 0; i < 9; i++){
        for(int j = 0; j < 9; j++){
            char c = board[i][j];
            if (c == '.') continue;
            int x = (c - '0') % 9;

            if (Row[i][x]) return 0;
            Row[i][x] = 1;

            if (Col[j][x]) return 0;
            Col[j][x] = 1;
            
            int bidx = (i / 3) * 3 + j / 3;
            
            if (Block[bidx][x]) return 0;
            Block[bidx][x] = 1;
        }
    }
    return 1;
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant