36. Valid Sudoku
Asked at 23Apple75Amazon59Bloomberg50Google47Microsoft45Meta41tcs27Confluent100Samsara100Wissen Technology100EarnIn84Snap80Verkada76Riot Games68Upstart67Zoho65Uber63Karat59PayPal58Walmart Labs53Oracle35Yandex28Goldman Sachs28
Problem
Given a partially filled 9×9 Sudoku board (digits '1'–'9' and '.' for empty), decide whether the filled cells are valid so far: no digit repeats within a row, a column, or any of the nine 3×3 boxes. The board doesn't have to be solvable.
Example: a standard puzzle with no repeats → true; the same board with two 8s in one 3×3 box → false
Keep a set for each row, column and 3×3 box. Box index = (r // 3) * 3 + c // 3. Any repeat → invalid.
Complexity: O(81) = O(1).
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
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):
v = board[r][c]
if v == ".":
continue
b = (r // 3) * 3 + c // 3
if v in rows[r] or v in cols[c] or v in boxes[b]:
return False
rows[r].add(v); cols[c].add(v); boxes[b].add(v)
return True
B = ["53..7....", "6..195...", ".98....6.", "8...6...3", "4..8.3..1",
"7...2...6", ".6....28.", "...419..5", "....8..79"]
board = [list(r) for r in B]
assert Solution().isValidSudoku(board) is True
board[0][0] = "8" # column 0 already has an 8
assert Solution().isValidSudoku(board) is False
class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] row = new boolean[9][9], col = new boolean[9][9], box = new boolean[9][9];
for (int r = 0; r < 9; r++)
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') continue;
int v = board[r][c] - '1', b = (r / 3) * 3 + c / 3;
if (row[r][v] || col[c][v] || box[b][v]) return false;
row[r][v] = col[c][v] = box[b][v] = true;
}
return true;
}
}
func isValidSudoku(board [][]byte) bool {
var rows, cols, boxes [9][9]bool
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
if board[r][c] == '.' {
continue
}
v, b := board[r][c]-'1', r/3*3+c/3
if rows[r][v] || cols[c][v] || boxes[b][v] {
return false
}
rows[r][v], cols[c][v], boxes[b][v] = true, true, true
}
}
return true
}