NeetCode #104LC-36MediumArrays & HashingNC 150NC 250
← Back to All Problems#104 · #36 · Valid Sudoku(有效的数独)
📌 Problem Statement & Constraints
Determine whether a partially filled 9x9 Sudoku board is valid. Only the filled cells need to be validated, against three rules: each row, each column, and each of the nine 3x3 sub-boxes must contain the digits 1-9 without repetition. Empty cells are represented by
'.'. Constraints: board.length == board[i].length == 9, and each cell is a digit or '.'.💡 Core Algorithmic Approaches
- The board size is fixed, so any solution is O(1); the interesting part is doing it cleanly in a single pass.
- Keep three families of hash sets: nine row sets, nine column sets, and nine box sets.
- Map each cell
(r, c)to its box index with(r // 3) * 3 + (c // 3). This is the classic trick worth memorising. - For each filled cell, test membership in all three sets; if any already contains the digit, the board is invalid. Otherwise insert into all three.
💻 Benchmark Python3 Implementation
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) # box index 0..8
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
# Bitmask variant: one integer per row/column/box instead of a set
class Solution2:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [0] * 9
cols = [0] * 9
boxes = [0] * 9
for r in range(9):
for c in range(9):
v = board[r][c]
if v == ".":
continue
bit = 1 << (ord(v) - ord("1"))
b = (r // 3) * 3 + (c // 3)
if rows[r] & bit or cols[c] & bit or boxes[b] & bit:
return False
rows[r] |= bit
cols[c] |= bit
boxes[b] |= bit
return True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) -- the board is a fixed 81 cells, so both variants run in constant time (O(81) with a tiny constant).
💾 Space Complexity
O(1) -- 27 sets (or 27 integers in the bitmask variant), independent of input size.
⚠️ Interview Pitfalls & Follow-ups
- Wrong box index formula: it is
(r // 3) * 3 + (c // 3), not(r // 3) + (c // 3) * 3or a division by 9. - Forgetting to skip
'.': the empty marker would be inserted into the sets and could trigger a false duplicate. - Validating only rows and columns: the 3x3 sub-box rule is the part candidates most often forget.
- Trying to solve the Sudoku: the problem only asks whether the current partial board is valid, not whether it is solvable.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
有效的数独
请你判断一个 9 × 9 的数独是否有效。只需要根据以下规则验证已经填入的数字是否有效即可:① 每一行包含 1-9 且不重复;② 每一列包含 1-9 且不重复;③ 每个 3 × 3 宫格内包含 1-9 且不重复。注意:数独部分空格已填入数字,空白格用 "." 表示;有效的数独不一定是可解的,只需满足上述规则。约束:board.length == 9,board[i].length == 9,board[i][j] 是数字或 "."。
核心要点
- 暴力逐格校验 :对每个已填格子,分别检查同行、同列、同宫是否重复。实现简单但需要重复扫描,时间 O(9^3) 量级。
- 一次遍历 + 三组集合(标准解) :为 9 行、9 列、9 个宫各维护一个集合。遍历每个格子,把数字分别插入行集合、列集合、宫集合;任一次插入发现已存在即返回 False。
- 宫编号的映射(本题核心技巧) :格子 (r, c) 所属宫的下标为 (r // 3) * 3 + (c // 3) ,取值范围 0..8。这是把二维坐标压成一维的经典手法。
- 位运算优化(进阶) :用 9 个整数的位掩码代替集合, mask |= 1 << d ,用 mask >> d & 1 判重。常数更小,是面试中展示功力的写法。
常见陷阱
- 宫编号公式写错 :常见错误是写成 (r // 3) + (c // 3) * 3 (行列颠倒)或 (r * 3 + c) // 3 。正确形式是 (r // 3) * 3 + (c // 3) 。
- 误判为「数独求解」 :本题只校验 已填数字是否合法 ,不要求解出数独,也不要求检查是否有解。把它当求解题会写出回溯,既慢又错。
- 用字符比较而非数字 :board 中是字符串 "1".."9",直接放进 set 判重是正确的;不要试图转 int,转与不转都不影响正确性,但混用(有的转有的不转)会导致误判。
- 被追问 如何扩展成求解器 时答不上来:应在校验基础上加回溯,按行优先选空格、尝试 1-9、失败回退;可用位掩码 + 候选数最少的格子优先(MRV 启发式)大幅剪枝。
参考实现
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) # 宫编号 0..8
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
# 位掩码版本(常数更小):
# rows = [0] * 9; cols = [0] * 9; boxes = [0] * 9
# bit = 1 << int(v)
# if rows[r] & bit or cols[c] & bit or boxes[b] & bit: return False
# rows[r] |= bit; cols[c] |= bit; boxes[b] |= bit