LeetCode #36 Medium

Valid Sudoku

Valid Sudoku is LeetCode 36 (Medium). You get a 9 × 9 Sudoku board where each cell is a digit 1–9 or . for empty. Return true if the filled cells break none of the three rules:

  • no digit twice in any row,
  • no digit twice in any column,
  • no digit twice in any of the nine 3 × 3 boxes.

Only the digits already on the board are checked. The board does not have to be full, and it does not have to be solvable.

Constraints
  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.
arrayhash-tablematrix
Open on LeetCode ↗
02

Intuition

Every filled cell belongs to exactly three groups: its row, its column and its box. Give each of the 27 groups a set of the digits seen in it so far. Then one pass over the board is enough: for each digit, ask its three sets whether they already hold it. A yes is a repeat, so the board is invalid. A no means the digit is new in all three groups, so record it in all three and move on.

The only real work is naming the box. Rows 0–2 form band 0, rows 3–5 band 1, rows 6–8 band 2, and columns split the same way. So the box number is (r // 3) * 3 + c // 3, which counts the boxes 0 to 8 left to right, top to bottom.

How to spot this pattern

Checking that no value repeats inside several overlapping groups is a job for one seen-set per group, all filled in a single scan. Sudoku Solver keeps the same 27 sets but uses them to decide which digits may go in an empty cell.

03

Approach

Try it first

Before reading on, work out which box the cell in row 4, column 7 belongs to, and write a formula that gives that number for any cell. Aim for one pass over the 81 cells.

1

Make one set per row, column and box

Create nine sets for rows, nine for columns and nine for boxes. Each set will hold the digits found so far in that group, so asking "has this group seen a 5?" is a single lookup.

2

Skip empty cells

Walk the board row by row. A . holds no digit, so it cannot repeat anything; move straight to the next cell.

3

Work out the box number

For a digit at row r and column c, compute b = (r // 3) * 3 + c // 3. The first part picks the band of three box rows and the second picks the box inside that band, so the nine boxes get the numbers 0 to 8.

4

Stop at the first repeat

If the digit is already in rows[r], cols[c] or boxes[b], return false. One repeat breaks a rule, so nothing later on the board can make it valid again.

5

Otherwise record the digit three times

Add the digit to all three sets, so any later copy in the same row, column or box is caught. If the scan reaches the end with no repeat, return true.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isValidSudoku(self, board: List[List[str]]) -> bool:
▶3 rows = [set() for _ in range(9)]
▶4 cols = [set() for _ in range(9)]
▶5 boxes = [set() for _ in range(9)]
▶6 for r in range(9):
▶7 for c in range(9):
▶8 d = board[r][c]
▶9 if d == ".":
▶10 continue
▶11 b = (r // 3) * 3 + c // 3
▶12 if d in rows[r] or d in cols[c] or d in boxes[b]:
▶13 return False
▶14 rows[r].add(d)
▶15 cols[c].add(d)
▶16 boxes[b].add(d)
▶17 return True
53762984631298row 0 has5column 0 has5box 0 has55 is new to row 0, column 0, box 0 → record it
cellrow 0, col 0
box0band 0 × 3 + 0
digit5
Empty cells are skipped, so the scan starts at the first digit. Row 0 sits in box band 0 and column 0 in box column 0, so this cell is in box 0. None of its three sets holds a 5 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 0 has53column 1 has3box 0 has533 is new to row 0, column 1, box 0 → record it
cellrow 0, col 1
box0band 0 × 3 + 0
digit3
Row 0 sits in box band 0 and column 1 in box column 0, so this cell is in box 0. None of its three sets holds a 3 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 0 has537column 4 has7box 1 has77 is new to row 0, column 4, box 1 → record it
cellrow 0, col 4
box1band 0 × 3 + 1
digit7
Row 0 sits in box band 0 and column 4 in box column 1, so this cell is in box 1. None of its three sets holds a 7 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 1 has6column 0 has56box 0 has5366 is new to row 1, column 0, box 0 → record it
cellrow 1, col 0
box0band 0 × 3 + 0
digit6
Row 1 sits in box band 0 and column 0 in box column 0, so this cell is in box 0. None of its three sets holds a 6 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 1 has62column 6 has2box 2 has22 is new to row 1, column 6, box 2 → record it
cellrow 1, col 6
box2band 0 × 3 + 2
digit2
Row 1 sits in box band 0 and column 6 in box column 2, so this cell is in box 2. None of its three sets holds a 2 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 2 has9column 1 has39box 0 has53699 is new to row 2, column 1, box 0 → record it
cellrow 2, col 1
box0band 0 × 3 + 0
digit9
Row 2 sits in box band 0 and column 1 in box column 0, so this cell is in box 0. None of its three sets holds a 9 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 2 has98column 2 has8box 0 has536988 is new to row 2, column 2, box 0 → record it
cellrow 2, col 2
box0band 0 × 3 + 0
digit8
Row 2 sits in box band 0 and column 2 in box column 0, so this cell is in box 0. None of its three sets holds a 8 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 3 has4column 3 has4box 4 has44 is new to row 3, column 3, box 4 → record it
cellrow 3, col 3
box4band 1 × 3 + 1
digit4
Row 3 sits in box band 1 and column 3 in box column 1, so this cell is in box 4. None of its three sets holds a 4 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 4 has6column 4 has76box 4 has466 is new to row 4, column 4, box 4 → record it
cellrow 4, col 4
box4band 1 × 3 + 1
digit6
Row 4 sits in box band 1 and column 4 in box column 1, so this cell is in box 4. None of its three sets holds a 6 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 4 has63column 8 has3box 5 has33 is new to row 4, column 8, box 5 → record it
cellrow 4, col 8
box5band 1 × 3 + 2
digit3
Row 4 sits in box band 1 and column 8 in box column 2, so this cell is in box 5. None of its three sets holds a 3 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 5 has1column 7 has1box 5 has311 is new to row 5, column 7, box 5 → record it
cellrow 5, col 7
box5band 1 × 3 + 2
digit1
Row 5 sits in box band 1 and column 7 in box column 2, so this cell is in box 5. None of its three sets holds a 1 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 6 has2column 2 has82box 6 has22 is new to row 6, column 2, box 6 → record it
cellrow 6, col 2
box6band 2 × 3 + 0
digit2
Row 6 sits in box band 2 and column 2 in box column 0, so this cell is in box 6. None of its three sets holds a 2 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 7 has9column 5 has9box 7 has99 is new to row 7, column 5, box 7 → record it
cellrow 7, col 5
box7band 2 × 3 + 1
digit9
Row 7 sits in box band 2 and column 5 in box column 1, so this cell is in box 7. None of its three sets holds a 9 yet, so the digit is recorded in all three to catch any later copy.
53762984631298row 8 has8column 8 has38box 8 has88 is new to row 8, column 8, box 8 → record it
cellrow 8, col 8
box8band 2 × 3 + 2
digit8
Row 8 sits in box band 2 and column 8 in box column 2, so this cell is in box 8. None of its three sets holds a 8 yet, so the digit is recorded in all three to catch any later copy.
53762984631298every digit checked, no repeats → valid
resulttrue
Each filled cell was checked against its row, column and box, and none of the 27 groups saw a digit twice. Empty cells do not matter, so the board is valid even though it is far from solved.
05

Common pitfalls

Adding the band numbers instead of combining them

✗ Wrong
b = r // 3 + c // 3
✓ Right
b = (r // 3) * 3 + c // 3

The sum only runs from 0 to 4, so different boxes share a number. Cells (0, 3) and (3, 0) both get box 1, and a 7 in each makes the board look invalid although the two 7s sit in different boxes.

Answering whether the board can be solved

✗ Wrong
run a Sudoku solver and return whether it succeeds
✓ Right
only check the digits already on the board for repeats

A board with no repeats can still have no solution, and this problem still wants true for it. Solving is also far slower than one scan of 81 cells.

06

Edge cases

A board with every cell empty

Nothing is ever added to a set, so no repeat is possible and the answer is true.

07

Complexity

Time
O(1)
Space
O(1)
The board is always 81 cells and each cell costs three set lookups at most, so the work does not grow with any input. For an n × n board the same method is O(n²) time and space.
08

Valid Sudoku FAQ

Can the 27 sets be replaced by something smaller?

Yes. Give each row, column and box one integer and use bit d for digit d. Testing is mask & (1 << d) and recording is mask |= 1 << d, which uses 27 integers in place of 27 sets. It is the same algorithm, only a more compact store.

Why do the C++ and Java versions use boolean arrays instead of sets?

The digits are only 1 to 9, so rows[r][d] with d = digit - 1 is a direct yes/no lookup. It does the same job as a set without hashing.