
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.
1public class Solution {
2 public bool IsValidSudoku(char[][] board) {
3 bool[,] rows = new bool[9, 9];
4 bool[,] cols = new bool[9, 9];
5 bool[,] boxes = new bool[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 int num = board[r][c] - '1';
12 int boxIndex = (r / 3) * 3 + c / 3;
13
14 if (rows[r, num] || cols[c, num] || boxes[boxIndex, num]) {
15 return false;
16 }
17 rows[r, num] = true;
18 cols[c, num] = true;
19 boxes[boxIndex, num] = true;
20 }
21 }
22 return true;
23 }
24}The C# implementation uses a similar logic to Java and C++, employing multidimensional arrays for efficient checking and marking of seen numbers.
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.
1defThis solution uses integers to record seen numbers in binary form. Each place represents whether a number has been seen (responding to the power of 2 in terms of bit location).