




Sponsored
Sponsored
This approach uses hash sets to track the unique numbers found in each row, column, and 3x3 sub-box. We iterate over each cell in the board, and check if the current value has been seen before in the current row, column, or sub-box. If it has, we return false. Otherwise, we add the value to the respective sets.
Time Complexity: O(1) because the board size is constant (9x9).
Space Complexity: O(1) due to the fixed size of additional data structures used.
1class Solution {
2    public boolean isValidSudoku(char[][] board) {
3        boolean[][] rows = new boolean[9][9];
4        boolean[][] cols = new boolean[9][9];
5        boolean[][] boxes = new boolean[9][9];
6
7        for (int r = 0; r < 9; r++) {
8            for (int c = 0; c < 9; c++) {
9                if (board[r][c] == '.') {
10                    continue;
11                }
12                int num = board[r][c] - '1';
13                int boxIndex = (r / 3) * 3 + c / 3;
14
15                if (rows[r][num] || cols[c][num] || boxes[boxIndex][num]) {
16                    return false;
17                }
18                rows[r][num] = true;
19                cols[c][num] = true;
20                boxes[boxIndex][num] = true;
21            }
22        }
23        return true;
24    }
25}This Java solution mirrors the C solution's logic but uses Java-specific constructs like arrays. The constraints check and updates are performed within nested loops.
This approach seeks to replace sets with bit manipulations to compress space usage for tracking seen numbers. We increment bits in an integer representing whether a digit has been seen in rows, columns, or boxes.
Time Complexity: O(1) as the board size and iteration steps remain constant.
Space Complexity: O(1) due to the integer used for tracking positions, which is constant.
1#include <vector>
using namespace std;
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int rows[9] = {0}, cols[9] = {0}, boxes[9] = {0};
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                if (board[r][c] == '.') continue;
                int bit = 1 << (board[r][c] - '1');
                int boxIndex = (r / 3) * 3 + c / 3;
                
                if ((rows[r] & bit) || (cols[c] & bit) || (boxes[boxIndex] & bit))
                    return false;
                rows[r] |= bit;
                cols[c] |= bit;
                boxes[boxIndex] |= bit;
            }
        }
        return true;
    }
};This C++ bit manipulation approach employs the same methodology as other languages, using integer arithmetic and bit shifts for rapid checks and updates.