Try it first — give it 20 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a 9×9 board where each cell is a digit '1'–'9' or '.' (empty). Return true if the filled cells follow Sudoku's three rules:
- No digit repeats in any row.
- No digit repeats in any column.
- No digit repeats in any of the nine 3×3 boxes.
You are not asked whether the puzzle can be solved — only whether what's on the board is legal right now.
Start with brute force
Check each rule separately: loop over the 9 rows with a fresh set, then the 9 columns, then the 9 boxes. That's three passes over 81 cells — already fast. The board size is fixed, so any reasonable approach is O(1). The interview is really about clean indexing, especially the box number.
Building the intuition
Instead of three passes, do one: every filled cell (r, c) belongs to:
- row
r - column
c - box
(r // 3) * 3 + (c // 3)
Keep a set of digits for each row, each column and each box. When you see a digit, check all three of its sets. If it's already in any of them, there's a clash.
Where does the box formula come from? r // 3 tells you which band of three rows you're in (0, 1 or 2), and c // 3 tells you which stack of three columns (0, 1 or 2). Numbering boxes left to right, top to bottom gives band × 3 + stack:
box 0 | box 1 | box 2 rows 0–2
-------+-------+-------
box 3 | box 4 | box 5 rows 3–5
-------+-------+-------
box 6 | box 7 | box 8 rows 6–8Cell (4, 7): band 4 // 3 = 1, stack 7 // 3 = 2 → box 1 × 3 + 2 = 5. ✓
The optimal approach
- Create 9 empty sets for rows, 9 for columns and 9 for boxes.
- For every cell
(r, c)holding a digitd:- compute
b = (r // 3) * 3 + c // 3 - if
dis already inrows[r],cols[c]orboxes[b], returnfalse - otherwise add
dto all three
- compute
- Return
true.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
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):
d = board[r][c]
if d == ".":
continue # empty cells never clash
b = (r // 3) * 3 + c // 3 # which 3x3 box (0..8)
if d in rows[r] or d in cols[c] or d in boxes[b]:
return False # digit repeated in a group
rows[r].add(d)
cols[c].add(d)
boxes[b].add(d)
return Trueclass Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
// seen[group][digit]: has this digit appeared in this row/col/box?
bool rows[9][9] = {}, cols[9][9] = {}, boxes[9][9] = {};
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') continue; // empty cells never clash
int d = board[r][c] - '1'; // '1'..'9' -> 0..8
int b = (r / 3) * 3 + c / 3; // which 3x3 box (0..8)
if (rows[r][d] || cols[c][d] || boxes[b][d]) return false;
rows[r][d] = cols[c][d] = boxes[b][d] = true;
}
}
return true;
}
};class Solution {
public boolean isValidSudoku(char[][] board) {
// seen[group][digit]: has this digit appeared in this row/col/box?
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] boxes = new boolean[9][9];
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') continue; // empty cells never clash
int d = board[r][c] - '1'; // '1'..'9' -> 0..8
int b = (r / 3) * 3 + c / 3; // which 3x3 box (0..8)
if (rows[r][d] || cols[c][d] || boxes[b][d]) return false;
rows[r][d] = cols[c][d] = boxes[b][d] = true;
}
}
return true;
}
}/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function (board) {
const rows = Array.from({ length: 9 }, () => new Set());
const cols = Array.from({ length: 9 }, () => new Set());
const boxes = Array.from({ length: 9 }, () => new Set());
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
const d = board[r][c];
if (d === ".") continue; // empty cells never clash
const b = Math.floor(r / 3) * 3 + Math.floor(c / 3); // which 3x3 box
if (rows[r].has(d) || cols[c].has(d) || boxes[b].has(d)) return false;
rows[r].add(d);
cols[c].add(d);
boxes[b].add(d);
}
}
return true;
};Dry run
On LeetCode's second example, the top-left cell is '8' and the cell at (3, 0) is also '8'.
| cell | digit | row set | col set | box | result |
|---|---|---|---|---|---|
| (0, 0) | 8 | rows[0] gets 8 | cols[0] gets 8 | box 0 gets 8 | ok |
| … | … | … | … | … | ok |
| (3, 0) | 8 | rows[3] fine | cols[0] already has 8 | box 3 | return false |
Complexity
- Time: O(1). The board is always 81 cells. For a general n×n board it's O(n²).
- Space: O(1). At most 81 digits stored three times. For n×n it's O(n²).
Edge cases and traps
- Empty cells. Skip
'.'— don't add it to any set. - The box index.
(r // 3) * 3 + c // 3, notr // 3 + c // 3(that collides boxes 1 and 3). - Integer division. In JavaScript,
r / 3is a decimal — useMath.floor(r / 3). - Solving it. A valid board can still be unsolvable. Don't overthink it.
Say it in the interview
"Every filled cell belongs to one row, one column and one box, where the box index is (r / 3) * 3 + c / 3 with integer division. I keep a set of seen digits for each of the 27 groups and do a single pass: if a digit is already in any of its three sets, the board is invalid. The board size is fixed, so it's constant time and space, or O(n²) for an n×n board."
Follow-ups interviewers ask
- "Can you use less memory?" Use a 9-bit mask per group instead of a set: digit
dsets bitd. - "Now solve the Sudoku." That's backtracking (LeetCode 37) — try a digit, recurse, undo on failure. You'll learn backtracking later in the plan.
- "Generalise to n² × n² boards?" Same idea, with box index
(r // n) * n + c // n.
Practise the same idea
This is Day 16 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free