Valid Sudoku
Master this topic with zero to advance depth.
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
Level I: Triple Pass
Intuition
Check rows, columns, and 3x3 boxes separately. For each check, use a boolean array or set to detect duplicates.
Detailed Dry Run
Check Row 0: [5, 3, ., 7, .] -> Unique numbers. OK. Check Col 0: [5, 6, ., 8, 4...] -> Unique. OK.
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.
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.
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 .
Detailed Dry Run
i=0, val='5'. mask = 1 << 5 (binary 00100000). Set bit in row[0], col[0], box[0].
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.