Valid Sudoku

Medium

Topics
ArrayHash TableMatrix

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

53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79
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

83..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79
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

  1. Maintain a set for each row, each column, and each box (box index = (r/3)*3 + c/3).
  2. For each filled cell, check all three sets; if the digit is already present, it is invalid.
  3. 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. Using r * 3 + c // 3 runs past 9 and raises IndexError -- 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 True
Asked at Apple PayPal Snap Uber
SensAI
Beta
Tap the mic to stop voice mode