Skip to main content

36. Valid Sudoku

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.

Each column must contain the digits 1-9 without repetition.

Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.

Solution

class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = defaultdict(set)
cols = defaultdict(set)
squares = defaultdict(set)
for r in range(9):
for c in range(9):
if board[r][c] == ".":
continue
if(board[r][c] in rows[r] or
board[r][c] in cols[c] or
board[r][c] in squares[(r // 3, c // 3)]):
return False
rows[r].add(board[r][c])
cols[c].add(board[r][c])
squares[(r//3,c//3)].add(board[r][c])
return True

Time Complexity: O(n)

Space Complexity: O(n)

Explanation

The idea is to process each cell in the matrix one by one and record the digits occurence in a dictionary for its specific row column and square.

One thing to note is the use of a tuple to serve as the key of the squares hashmap. Where (0,0) refers to the top left square, (0,1) refers to the top mid square, etc. The use of floor division is used to figure out what square a r,c pair fits in.