1. Triple Pass Check (Row, Col, Box Separately)
Intuition
Validate each constraint separately: first verify all 9 rows for duplicates, then all 9 columns, then all 9 3x3 boxes.
Algorithm
- Check rows: For each row
r, use a boolean array to check digits 1-9. - Check cols: For each col
c, use a boolean array to check digits 1-9. - Check boxes: For each 3x3 subgrid starting at
(br, bc), check digits 1-9. - If any duplicate is detected, return
false. - If all pass, return
true.
Triple Pass Check Trace
2 of 2 questions left todayPass 1 (Rows): Iterate rows 0 to 8
Pass 1 (Rows): Iterate rows 0 to 8. For each row, use a HashSet seen.
#include <iostream>#include <vector>#include <unordered_set> class Solution {public: bool isValidSudoku(std::vector<std::vector<char>>& board) { // 1. Check rows for (int r = 0; r < 9; ++r) { std::vector<bool> seen(10, false); for (int c = 0; c < 9; ++c) { if (board[r][c] != '.') { int val = board[r][c] - '0'; if (seen[val]) return false; seen[val] = true; } } } // 2. Check cols for (int c = 0; c < 9; ++c) { std::vector<bool> seen(10, false); for (int r = 0; r < 9; ++r) { if (board[r][c] != '.') { int val = board[r][c] - '0'; if (seen[val]) return false; seen[val] = true; } } } // 3. Check 3x3 boxes for (int box = 0; box < 9; ++box) { std::vector<bool> seen(10, false); int startR = (box / 3) * 3; int startC = (box % 3) * 3; for (int r = 0; r < 3; ++r) { for (int c = 0; c < 3; ++c) { char cell = board[startR + r][startC + c]; if (cell != '.') { int val = cell - '0'; if (seen[val]) return false; seen[val] = true; } } } } return true; }}; int main() { Solution sol; std::vector<std::vector<char>> board = { {'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; std::cout << (sol.isValidSudoku(board) ? "true" : "false") << std::endl; // Output: true return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Triple Pass Check (Row, Col, Box Separately). - Space complexity:
O(1)— Space complexity for Triple Pass Check (Row, Col, Box Separately).
Why Brute Force Doesn't Scale:
While 81 iterations is small, heap allocations and hash function computations add unnecessary CPU cycle overhead.
Bitmasking with 9-bit integers executes in under 500 nanoseconds using standard CPU register bitwise instructions.