Skip to content

36.Valid Sudoku.cpp #63

Open
shafaq16 wants to merge 1 commit intoSjxSubham:mainfrom
shafaq16:patch-2
Open

36.Valid Sudoku.cpp #63
shafaq16 wants to merge 1 commit intoSjxSubham:mainfrom
shafaq16:patch-2

Conversation

@shafaq16
Copy link
Contributor

@shafaq16 shafaq16 commented Oct 2, 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 '.'.
Convert digit '1'–'9' into index 0–8.
If digit already exists in the row/col/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 reading 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 is immediately invalid.
Using bitsets makes this efficient since checking/setting bits is O(1).
It’s basically like running 3 parallel hash checks while scanning the board once.

Solution in Code (C++)

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& 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; 
                // Convert the character digit to an index (0-8) 0 for 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;
    }
};

This was referenced Oct 2, 2025
@SjxSubham
Copy link
Owner

SjxSubham commented Oct 3, 2025

@shafaq16 Thanks for the PR

Star the repo ⭐

Happy HAcktober... keep contributing...

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 3, 2025
@shafaq16
Copy link
Contributor Author

shafaq16 commented Oct 3, 2025

hey @SjxSubham kindly merge my pr #63

@SjxSubham SjxSubham mentioned this pull request Oct 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants