Valid Sudoku
Difficulty: Medium · Pattern: Matrix · LeetCode #36
Determine whether a partially filled 9×9 Sudoku board is valid: no digit repeats within any row, column or 3×3 box. Only the filled cells need to be checked. The board doesn't have to be solvable.
Example
text
(the standard example board) → true
same board with board[0][0] = "8" (a second 8 in column 0 / box 0) → falseHints
- Box index of
(r, c):(r // 3) * 3 + c // 3. - One pass is enough: keep 27 sets (9 rows, 9 columns, 9 boxes).
Approach
For every filled cell with digit d, check whether d is already in rows[r], cols[c] or boxes[b]. If so, return false. Otherwise add it to all three.
A compact alternative stores the strings "r{r}:{d}", "c{c}:{d}", "b{b}:{d}" in one set. Bitmasks (1 << d) give the fastest version. The work is O(81), i.e. constant.
Complexity
Time: O(81). Space: O(81).
Python solution
def isValidSudoku(board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
d = board[r][c]
if d == '.':
continue
b = r // 3 * 3 + c // 3
if d in rows[r] or d in cols[c] or d in boxes[b]:
return False
rows[r].add(d); cols[c].add(d); boxes[b].add(d)
return TrueJavaScript solution
function isValidSudoku(board) {
const rows = new Array(9).fill(0), cols = new Array(9).fill(0), boxes = new Array(9).fill(0);
for (let r = 0; r < 9; r++) for (let c = 0; c < 9; c++) {
const ch = board[r][c];
if (ch === '.') continue;
const bit = 1 << Number(ch), b = 3 * Math.floor(r / 3) + Math.floor(c / 3);
if (rows[r] & bit || cols[c] & bit || boxes[b] & bit) return false;
rows[r] |= bit; cols[c] |= bit; boxes[b] |= bit;
}
return true;
}