Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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];
};