
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.
1function isValidSudoku(board) {
2 const rows = new Array(9).fill(0).map(() => new Set());
3 const cols = new Array(9).fill(0).map(() => new Set());
4 const boxes = new Array(9).fill(0).map(() => new Set());
5
6 for (let r = 0; r < 9; r++) {
7 for (let c = 0; c < 9; c++) {
8 if (board[r][c] === '.') continue;
9 const num = board[r][c];
10 const boxIndex = Math.floor(r / 3) * 3 + Math.floor(c / 3);
11
12 if (rows[r].has(num) || cols[c].has(num) || boxes[boxIndex].has(num)) {
13 return false;
14 }
15 rows[r].add(num);
16 cols[c].add(num);
17 boxes[boxIndex].add(num);
18 }
19 }
20 return true;
21}In JavaScript, we use arrays of sets for each row, column, and box. This allows us to efficiently check for duplicates as we iterate through the board.
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.