</>

36. Valid Sudoku

Medium NeetCode 150
Arrays & Hashing Time O(1) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Arrays & Hashing
Time
O(1)
Space
O(1)

Standard Solution (C++)

SummaryGiven a 9x9 partially filled Sudoku board, determine whether the current configuration is valid by checking that no digit 1-9 is repeated in any row, any column, or any of the nine 3x3 sub-boxes. Empty cells (marked with '.') are ignored.

Approach
  • Use three arrays of nine bitmasks — one per row, one per column, one per 3x3 box — to track which digits have been seen.
  • For each non-empty cell, compute the digit (0-indexed) and the box index (row/3)*3 + col/3, then check all three corresponding bitmasks for a collision.
  • If any digit is already recorded in the same row, column, or box, return false; otherwise set the corresponding bit and continue.
  • Because the board is always exactly 81 cells, every loop is bounded by a constant, making the overall work O(1).
#include <vector>
#include <array>
using namespace std;

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        // Each entry is a bitmask for digits 1-9 (bit i-1 represents digit i)
        array<int, 9> rows{}, cols{}, boxes{};

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

                int digit = board[r][c] - '1';   // 0-indexed digit
                int mask   = 1 << digit;
                int box    = (r / 3) * 3 + (c / 3);

                // Collision in row, column, or box?
                if ((rows[r] & mask) || (cols[c] & mask) || (boxes[box] & mask))
                    return false;

                rows[r]    |= mask;
                cols[c]    |= mask;
                boxes[box] |= mask;
            }
        }
        return true;
    }
};
Time O(1) — the board is always 9x9 (81 cells), so all work is bounded by a constant. Space O(1) — three fixed-size arrays of nine integers each, independent of any variable input.

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        std::unordered_set<char> uset; 

        // search rows
        for(int row=0; row<9; ++row){
            for(int col=0; col<9; ++col){
                char c=board[row][col];
                if(c=='.')
                    continue;
                else if(uset.count(c))
                    return false;
                else
                    uset.insert(c);
            }
            uset.clear();
        }

        // search cols
        for(int col=0; col<9; ++col){
            for(int row=0; row<9; ++row){
                char c=board[row][col];
                if(c=='.')
                    continue;
                else if(uset.count(c))
                    return false;
                else
                    uset.insert(c);
            }
            uset.clear();
        }

        // search grids
        for(int i=0; i<3; ++i){
            for(int j=0; j<3; ++j){
                for(int row=0; row<3; ++row){
                    for(int col=0; col<3; ++col){
                        char c=board[i*3+row][j*3+col];
                        if(c=='.')
                            continue;
                        else if(uset.count(c))
                            return false;
                        else
                            uset.insert(c);
                    }
                }
                uset.clear();
            }
        }

        return true;
    }
};

// Time Complexity: O(1), since the board size is fixed (9x9).
// Space Complexity: O(1), since the maximum size of the hash set is limited to 9 elements for each row, column, or grid.
Time O(1) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern