Skip to content

Conversation

@Athting
Copy link

@Athting Athting commented Oct 4, 2025

Solved #51
Problem: 36. Valid Sudoku

// Approach: Hashing with Bitsets

// Implementation Idea

// Use 3 arrays of bitsets (or boolean 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 cell is '.'
// - Convert digit '1'–'9' → index 0–8
// - If digit already exists in row/col/block → invalid
// - Else, mark it as used in all three
// If traversal completes with no conflicts → valid board.
// Block index formula: (r / 3) * 3 + (c / 3)

// Intuition

// Think of it as tracking duplicates across three dimensions:
// - Row-wise
// - Column-wise
// - Block-wise

// As we read each cell, we “register” that digit in its row, column, and block.
// If any duplicate appears, it violates Sudoku rules.
// Bitsets make checks and updates O(1) — effectively running 3 hash lookups in parallel.

Complexity

// Time Complexity: O(9×9) = O(1)
// Space Complexity: O(9×3) = O(1)

Code Implementation

class Solution {
public:
bool isValidSudoku(vector<vector>& board) {
vector<bitset<9>> row(9), col(9), block(9);

    for (int r = 0; r < 9; ++r) {
        for (int c = 0; c < 9; ++c) {
            if (board[r][c] == '.') continue;

            int num = board[r][c] - '1';              // convert '1'-'9' → 0-8
            int blockIdx = (r / 3) * 3 + (c / 3);    // find block index

            if (row[r][num] || col[c][num] || block[blockIdx][num])
                return false; // duplicate found

            row[r][num] = col[c][num] = block[blockIdx][num] = 1;
        }
    }
    return true;
}

};

@SjxSubham
Copy link
Owner

SjxSubham commented Oct 4, 2025

@Athting maintain proper PR description format ...see other closed PR for ref.

the Problem Id.name should be mentioned in the title of the PR... and star the repo as well

@Athting
Copy link
Author

Athting commented Oct 4, 2025

@SjxSubham I have updated same pr plz check

@SjxSubham
Copy link
Owner

@SjxSubham I have updated same pr plz check

fix the file naming format... and remove comments from PR description [Approach, Intuition]... the PR title also should be same as file name

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.

2 participants