Valid Sudoku (LeetCode 36): Solution and Explanation

Medium
Array
Hash Table
Matrix

Given a partially filled 9 by 9 Sudoku board, decide whether the filled cells break any rule: no digit may repeat within a row, a column, or one of the nine 3 by 3 boxes. You do not need to check whether the puzzle can be solved.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The rules translate directly into 27 small uniqueness checks: nine rows, nine columns and nine boxes, each of which must not contain a repeated digit. The simplest code checks them separately, scanning each row with a fresh set, then each column, then each box. That is perfectly correct and runs over the board three times. The question is whether you can do all three checks in one pass.

You can, as long as you know which row, column and box each cell belongs to. The row and column are just r and c. The box needs a small formula. Integer division by 3 turns a row index 0 to 8 into a band 0 to 2, and the same for columns. Combining them as (r // 3) * 3 + (c // 3) numbers the boxes 0 through 8 from left to right and top to bottom. With that, every cell touches exactly three sets, one per constraint.

So the algorithm keeps 27 sets: rows[r], cols[c] and boxes[b]. For each filled cell, if its digit is already present in any of its three sets, the board is invalid and you return immediately. Otherwise you add the digit to all three and move on. Empty cells marked with . are skipped, because blanks never conflict. If the scan finishes with no conflict, the board is valid.

Approach: One-pass hash sets for rows, columns and boxes

  1. Create three lists of nine empty sets: rows, cols and boxes.
  2. Loop over every row r and column c from 0 to 8, reading val = board[r][c].
  3. If val is ., skip the cell.
  4. If val is already in rows[r] or cols[c], return False.
  5. Compute box_idx = (r // 3) * 3 + (c // 3). If val is already in boxes[box_idx], return False.
  6. Add val to rows[r], cols[c] and boxes[box_idx].
  7. After all 81 cells are processed, return True.

Step-by-step example

The standard valid example board, with an extra "8" placed at row 2, column 0 to make it invalid (the board already has "8" at row 2, column 2).
  1. Row 0 is processed first: 5 at (0,0) goes into rows[0], cols[0] and boxes[0]; 3 at (0,1) into rows[0], cols[1], boxes[0]; 7 at (0,4) into box (0 // 3) * 3 + (4 // 3) = 1.
  2. Row 1 adds 6 at (1,0) to rows[1], cols[0] and boxes[0], then 1, 9 and 5 to box 1.
  3. Row 2 starts at (2,0) with our extra 8. rows[2] and cols[0] do not contain 8 yet, and box 0 holds {5, 3, 6}, so 8 is added everywhere.
  4. At (2,1) the 9 is new for row 2, column 1 and box 0, so it is added.
  5. At (2,2) the original 8 appears. rows[2] already contains 8, so the function returns False.

Code: Python, Java, C++

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
7        for r in range(9):
8            for c in range(9):
9                val = board[r][c]
10                if val == ".":
11                    continue
12                
13                if val in rows[r]:
14                    return False
15                if val in cols[c]:
16                    return False
17                
18                box_idx = (r // 3) * 3 + (c // 3)
19                if val in boxes[box_idx]:
20                    return False
21                
22                rows[r].add(val)
23                cols[c].add(val)
24                boxes[box_idx].add(val)
25        
26        return True

Time and space complexity

Time

O(1)

The board is always 9 by 9, so the loop runs exactly 81 times with constant work per cell. For a general n by n board the same algorithm would be O(n²).

Space

O(1)

The 27 sets hold at most 81 digits in total, a fixed amount. For an n by n board this would be O(n²).

Other approaches

Three separate passes (time O(1), space O(1))

Validate all rows, then all columns, then all boxes, each with a fresh set. It reads the board three times but is very easy to debug and explain.

Bitmasks instead of sets (time O(1), space O(1))

Represent each row, column and box as a 9-bit integer where bit d means digit d has been seen. Checks and inserts become bitwise operations, which is faster and uses 27 integers instead of 27 sets.

Common mistakes

  • Computing the box index as r // 3 + c // 3. That maps several different boxes to the same number; the row band must be multiplied by 3.
  • Trying to solve the puzzle or verifying that every row contains all nine digits. The task only asks whether the filled cells conflict.
  • Forgetting to skip . cells, which makes every row with two blanks look like a duplicate.
  • Treating the digits as integers in one place and strings in another. The board stores characters, so keep them as strings or convert consistently.

Frequently asked questions

How do you calculate the 3x3 box index in Sudoku?

Use (r // 3) * 3 + (c // 3). The first part picks the band of three box rows and the second picks the box within that band, giving numbers 0 to 8.

Does a valid Sudoku board have to be solvable?

No. This problem only checks that no filled digit repeats in a row, column or box. A board can pass that test and still have no solution.

What is the time complexity of Valid Sudoku?

Because the board size is fixed at 81 cells, it is O(1). Generalized to an n by n grid, it is O(n²).

Can you check rows, columns and boxes in one pass?

Yes. Keep a set for each of them and, for every filled cell, check and update its row set, column set and box set at the same time.