Skip to content

LeetCode 36 - Valid Sudoku

Difficulty: medium

Table of Contents

Open Table of Contents

Problem

Given a 9x9 Sudoku board, determine if it is valid. A Sudoku board is valid if:

Note:

Example 1:

Input:
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true

Example 2:

Input:
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false

Constraints:

Explanation/Approach

Using Hash Sets:

Solution: Using Hash Sets

from collections import defaultdict

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        rows = defaultdict(set)
        columns = defaultdict(set)
        boxes = defaultdict(set)

        for i in range(9):
            for j in range(9):
                num = board[i][j]
                if num != '.':
                    box_index = (i // 3) * 3 + j // 3
                    if num in rows[i] or num in columns[j] or num in boxes[box_index]:
                        return False
                    rows[i].add(num)
                    columns[j].add(num)
                    boxes[box_index].add(num)
        return True

Time and Memory Complexity

Visual Representation

For Example 1: