
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.
1class
This solution emulates the bit manipulation logic through Java, which makes use of integer operation for fast checks of duplicated values among rows, columns, and boxes.