Validate Sudoku Board Rows Columns and Boxes in Python

Validate a 9x9 Sudoku board by checking that each row, column, and 3x3 box contains the numbers 1 through 9 exactly once.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 11 views 0 copies

Python code

40 lines
Python 3.9+
def validate_sudoku(board):
    def is_valid_group(group):
        return sorted(group) == list(range(1, 10))

    def get_columns():
        return [[board[r][c] for r in range(9)] for c in range(9)]

    def get_boxes():
        boxes = []
        for box_row in range(0, 9, 3):
            for box_col in range(0, 9, 3):
                box = [
                    board[r][c]
                    for r in range(box_row, box_row + 3)
                    for c in range(box_col, box_col + 3)
                ]
                boxes.append(box)
        return boxes

    all_groups = board + get_columns() + get_boxes()
    return all(is_valid_group(group) for group in all_groups)


if __name__ == "__main__":
    valid_board = [
        [5, 3, 4, 6, 7, 8, 9, 1, 2],
        [6, 7, 2, 1, 9, 5, 3, 4, 8],
        [1, 9, 8, 3, 4, 2, 5, 6, 7],
        [8, 5, 9, 7, 6, 1, 4, 2, 3],
        [4, 2, 6, 8, 5, 3, 7, 9, 1],
        [7, 1, 3, 9, 2, 4, 8, 5, 6],
        [9, 6, 1, 5, 3, 7, 2, 8, 4],
        [2, 8, 7, 4, 1, 9, 6, 3, 5],
        [3, 4, 5, 2, 8, 6, 1, 7, 9],
    ]
    invalid_board = [row[:] for row in valid_board]
    invalid_board[0][0] = 1

    print(f"Valid board: {validate_sudoku(valid_board)}")
    print(f"Invalid board: {validate_sudoku(invalid_board)}")

Output

stdout
Valid board: True
Invalid board: False

How it works

The solution defines a helper is_valid_group that checks a list of 9 numbers is exactly 1-9 by sorting and comparing against list(range(1, 10)). It builds all rows from the input board, columns with a list comprehension over range(9), and 3x3 boxes by stepping through the board in three-row/three-column chunks. Combining all three lists into one all_groups list, the function returns True only if every group passes the validation check. This approach is O(81) for the group checks and cleanly separates row, column, and box logic.

Common mistakes

  • Forgetting to validate the 3x3 boxes, only checking rows and columns
  • Using `set(group)` instead of `sorted(group)` which incorrectly allows duplicates like [1,1,2,...]
  • Off-by-one errors when slicing box coordinates (using 0-2, 3-5, 6-8 boundaries)
  • Assuming the input contains integers when it might contain strings or None

Variations

  1. Use `set(group) == set(range(1, 10))` for a more concise but less order-exploiting check
  2. Validate on the fly while reading the board with early exit on first failure to save time

Real-world use cases

  • Building a Sudoku puzzle generator that needs to verify automatically generated grids meet rules before publishing them.
  • Checking user-submitted puzzle solutions in a web game backend before scoring or advancing to the next level.
  • Validating grid data coming from an OCR or image-recognition service that parses printed Sudoku puzzles for digit verification.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.