Valid Sudoku
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Arrays & Hashing.
Valid Sudoku
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Visual Representation
Box Index Formula: (row / 3) * 3 + (col / 3)
Row 0-2, Col 0-2 -> Box 0
Row 0-2, Col 3-5 -> Box 1
Row 3-5, Col 0-2 -> Box 3Examples
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[.".","9","8",".",".",".",".","6","."]
...]
Output: true
Approach 1
Level I: Triple Pass
Intuition
Check rows, columns, and 3x3 boxes separately. For each check, use a boolean array or set to detect duplicates.
⏱ O(N²)💾 O(N)
Detailed Dry Run
Check Row 0: [5, 3, ., 7, .] -> Unique numbers. OK.
Check Col 0: [5, 6, ., 8, 4...] -> Unique. OK.
Approach 2
Level II: Single Pass with HashSets
Intuition
Iterate over the board once. Maintain arrays of HashSets for rows, columns, and boxes to track seen digits.
⏱ O(N²)💾 O(N²)
Detailed Dry Run
i=4, j=4, val='5'
- Seen in row 4? No.
- Seen in col 4? No.
- Seen in box (4/3)*3 + 4/3 = 4? No. Store it.
Approach 3
Level III: Bitmasking (Optimal Space)
Intuition
Use an integer (32-bit) as a bitmask for each row, column, and box. The -th bit represents the presence of digit .
⏱ O(N²)💾 O(N) - 27 integers total.
Detailed Dry Run
i=0, val='5'. mask = 1 << 5 (binary 00100000). Set bit in row[0], col[0], box[0].
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.