Skip to content

Valid Sudoku

LeetCode

01 · Question

Given a 9x9 grid, board, representing a Sudoku, return true if the board does not have any conflicts and false otherwise. The board contains only numbers between 0 and 9 in each cell, with 0's denoting empty cells.

A conflict is a duplicate number (other than 0) along a row, a column, or a 3x3 subgrid.

Example 1:

  • Input: A valid Sudoku board.
  • Output: true

Example 2:

  • Input: A board with duplicates in the first row.
  • Output: false

02 · Solution

Reference solution

1def isValidSudoku(board: List[List[str]]) -> bool:
2 rows = [set() for _ in range(9)]
3 cols = [set() for _ in range(9)]
4 boxes = [set() for _ in range(9)]
5
6 for r in range(9):
7 for c in range(9):
8 val = board[r][c]
9 if val == ".":
10 continue
11
12 # Check row
13 if val in rows[r]: return False
14 rows[r].add(val)
15
16 # Check col
17 if val in cols[c]: return False
18 cols[c].add(val)
19
20 # Check box
21 idx = (r // 3) * 3 + (c // 3)
22 if val in boxes[idx]: return False
23 boxes[idx].add(val)
24
25 return True