easy +10 pts

Valid Sudoku Board

Check if a 9x9 Sudoku board follows the classic validity rules.

Write a function `is_valid_sudoku(board)` that takes a 9x9 list of lists representing a partially filled Sudoku board and returns `True` if the board is valid according to Sudoku rules, `False` otherwise. The board is a list of 9 lists, each containing 9 elements. Each element is a digit from '1' to '9' or '.' (empty cell). A valid Sudoku board must satisfy all three conditions: 1. Each row contains the digits 1-9 without repetition. 2. Each column contains the digits 1-9 without repetition. 3. Each of the nine 3x3 sub-boxes (regions) contains the digits 1-9 without repetition. Only the filled cells need to be validated according to these rules. Empty cells ('.') are ignored. You may assume the input is always a 9x9 board as described. Do not verify that the board is solvable. Implement the function and return a boolean.

Constraints

The input is always a 9x9 list of lists. Each element is a character from '1' to '9' or '.'. There are no other characters. The function should run in O(1) time (constant board size) and O(1) extra space.

Example

>>> is_valid_sudoku([
...     ['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']
... ])
True

>>> is_valid_sudoku([
...     ['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']
... ])
False  # duplicate '8' in column 0
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use Python sets to detect duplicates in each row, column, and 3x3 box.
For each cell, you can derive the box index as (row // 3, col // 3).
You can validate all rows and columns in one pass, and boxes in a second pass or by using a set keyed by (box_row, box_col, digit).
Remember that '.' represents an empty cell and should be ignored.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.