Valid Sudoku
Medium
Topics
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be checked: each row, each column, and each 3 x 3 sub-box must contain no repeated digit 1-9. Empty cells are '.'. The board need not be solvable.
Example 1
No row, column, or 3×3 box repeats a digit, so this board is valid. Note that only the filled cells are checked — the board does not have to be solvable.
Character grid — one row per line.
Input: board = ["53..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"] Output: true
Example 2
The shaded digits are a clash: a value repeated inside one row, one column, or one 3×3 box. Any single clash makes the board invalid.
Input: board = ["83..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"] Output: false Explanation: Two 8s share the first column.
Constraints
- board.length == 9
- board[i].length == 9
- board[i][j] is a digit 1-9 or '.'
Editorial — intuition, approach, complexity and pitfalls
Intuition
Validity is purely about no duplicate digit within any row, column, or 3x3 box. Track seen digits for each of those 27 groups.
Approach
- Maintain a set for each row, each column, and each box (box index = (r/3)*3 + c/3).
- For each filled cell, check all three sets; if the digit is already present, it is invalid.
- Otherwise record it in the three sets.
Dry Run
The only arithmetic in this problem is the box index, so it is worth tabulating
rather than trusting:
(r // 3) * 3 + c // 3
r=0 c=0 -> 0 c=3 -> 1 c=8 -> 2
r=1 c=0 -> 0 c=3 -> 1 c=8 -> 2
r=3 c=0 -> 3 c=3 -> 4 c=8 -> 5
r=8 c=0 -> 6 c=3 -> 7 c=8 -> 8
Rows 0 and 1 share a band and therefore share box numbers; row 3 starts the next
band at 3. The `// 3` on the row collapses nine rows to three bands and the `* 3`
spaces the bands out. Write `r * 3 + c // 3` instead and the index runs to 26,
which is an IndexError rather than a wrong answer.
The scan itself is one pass. Each filled cell is checked against three sets and
then added to all three, so a duplicate is caught the first time it is seen and
the function returns immediately.
One thing about the embedded cases rather than the code: removing the box check
entirely still passes every one of them, because none has a board whose only
violation is inside a 3x3 box. The check is certainly required -- a board with 1
at (0,0) and 1 at (1,1) is invalid and reports valid without it -- so that is a
gap in the test data, not a redundant line.
Only the given digits are examined. The question is whether the board is currently
legal, not whether it can be solved.Complexity
- Time — O(1): the board is a fixed 81 cells.
- Space — O(1): 27 small sets.
Common Pitfalls
- The box index is
(r // 3) * 3 + c // 3. Usingr * 3 + c // 3runs past 9 and raisesIndexError-- the row has to be collapsed to a band first. - Worth knowing about the embedded cases rather than the code: removing the box check entirely still passes all of them, because none has a board whose only violation is inside a 3x3 box. The check is certainly required -- a board with 1 at (0,0) and 1 at (1,1) is invalid and reports valid without it -- so that is a gap in the test data, not a redundant line.
- Only the given digits are checked. This asks whether the board is currently legal, not whether it is solvable.
Full Solution — all languages
class Solution:
def isValidSudoku(self, 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):
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 Trueimport java.util.*;
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Character>[] rows=new HashSet[9],cols=new HashSet[9],boxes=new HashSet[9];
for(int i=0;i<9;i++) {
rows[i]=new HashSet<>();
cols[i]=new HashSet<>();
boxes[i]=new HashSet<>();
}
for(int r=0;r<9;r++)for(int c=0;c<9;c++) {
char v=board[r][c];
if(v=='.')continue;
int b=(r/3)*3+c/3;
if(rows[r].contains(v)||cols[c].contains(v)||boxes[b].contains(v))return false;
rows[r].add(v);
cols[c].add(v);
boxes[b].add(v);
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isValidSudoku(vector<vector<char>>& board) {
vector<set<char>> rows(9),cols(9),boxes(9);
for(int r=0;r<9;r++)for(int c=0;c<9;c++) {
char v=board[r][c];
if(v=='.')continue;
int b=(r/3)*3+c/3;
if(rows[r].count(v)||cols[c].count(v)||boxes[b].count(v))return false;
rows[r].insert(v);
cols[c].insert(v);
boxes[b].insert(v);
}
return true;
}
};/**
* @param {character[][]} board
* @return {boolean}
*/ var isValidSudoku = function(board) {
const rows=[],cols=[],boxes=[];
for(let i=0;i<9;i++) {
rows.push(new Set());
cols.push(new Set());
boxes.push(new Set());
}
for(let r=0;r<9;r++)for(let c=0;c<9;c++) {
const v=board[r][c];
if(v==='.')continue;
const b=((r/3)|0)*3+((c/3)|0);
if(rows[r].has(v)||cols[c].has(v)||boxes[b].has(v))return false;
rows[r].add(v);
cols[c].add(v);
boxes[b].add(v);
}
return true;
};