Skip to content

Valid Sudoku

Check that a partly filled 9 x 9 Sudoku board breaks no rule, with one set per row, column and box.

MediumHashing
Solve on LeetCode

The problem

You get a 9 x 9 board where each cell holds a digit from 1 to 9 or a "." for an empty cell. Return true if the filled cells break no Sudoku rule: no digit repeats within a row, within a column, or within any of the nine 3 x 3 boxes. Only the digits already placed matter; the board does not have to be solvable. In the examples, each row of the board is written as one 9-character string.

Input board, row by row: "..6......", "..8.61..5", ".9.2.4...", "...8...3.", "63....9.8", "8.9.43.5.", ".7.......", "4......89", "9.....37."

Output true

No digit appears twice in any row, column or 3 x 3 box.

Input board, row by row: ".86......", "..8.61..5", ".9.2.4...", "...8...3.", "63....9.8", "8.9.43.5.", ".7.......", "4......89", "9.....37."

Output false

The same board with an 8 added at row 0, column 1. That row and column are still fine, but the top-left box now holds two 8s; the other one is at row 1, column 2.

How to spot the pattern

  • You must catch repeats inside several groups at once: every row, every column and every box.
  • Each check is "have I already seen this digit in this group?", which is what a set answers.

The idea

Every filled cell belongs to exactly three groups: its row, its column and its 3 x 3 box. Keep a set of seen digits for each of the 27 groups and check every digit against its three sets as you scan the board. The box of cell (r, c) is number (r / 3) * 3 + c / 3 with integer division, which numbers the nine boxes 0 to 8. Since the digits are only 1 to 9, each set can also be a row of 9 true/false flags, as in the Java and C++ code.

Brute force: For every filled cell, rescan its row, column and box for the same digit, which costs about 24 comparisons per cell instead of 3 set lookups.

Step by step

  1. 1Make 9 empty sets for the rows, 9 for the columns and 9 for the boxes.
  2. 2Scan every cell, skipping the empty ones.
  3. 3For a digit at (r, c), work out its box b = (r / 3) * 3 + c / 3.
  4. 4If the digit is already in the set for row r, column c or box b, return false.
  5. 5Otherwise add it to those three sets; after the scan, return true.

See the pattern move

The hashing pattern on a small example. Step through it, or press play.

Code

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):
                digit = board[r][c]
                if digit == ".":
                    continue
                b = (r // 3) * 3 + c // 3  # boxes are numbered 0 to 8
                if digit in rows[r] or digit in cols[c] or digit in boxes[b]:
                    return False
                rows[r].add(digit)
                cols[c].add(digit)
                boxes[b].add(digit)
        return True

Complexity

Time

O(1)

Space

O(1)

The board is always 9 x 9, so the scan touches 81 cells and the sets hold at most 243 digits; for an n x n board the same method is O(n^2) time and space.

Watch out for

  • Getting the box number wrong: r / 3 + c / 3 gives boxes (0, 1) and (1, 0) the same number; you need (r / 3) * 3 + c / 3.
  • Trying to decide whether the board can be solved: the task only asks about the digits already on it.
  • Treating the cells as numbers: they hold characters like '5' and '.', so in Java and C++ subtract '1' to turn a digit into a slot from 0 to 8.

Follow-up questions

Can you use less memory?

Give each row, column and box a 9-bit mask, where bit d is set once digit d has appeared. A check is mask & bit and an insert is mask |= bit, so 27 integers replace the sets.

How would you go on to solve the Sudoku?

Backtracking: put a digit in an empty cell, check it against the same row, column and box records, recurse, and undo the placement when it leads nowhere. N-Queens uses the same choose, check and undo loop.

In Hinglish

Har digit teen jagah check karo: apni row, apna column aur apna 3x3 box. Kahin bhi pehle se mila toh board invalid hai.

Related problems