Python coding

Check a half-filled sudoku

A 9×9 sudoku board is given as 9 strings of 9 characters each: a digit 1–9, or . for an empty cell. Return True if the filled cells break no rule: no digit appears twice in the same row, in the same column, or in the same one of the nine 3×3 boxes. Ignore empty cells, and don't check whether the board can be solved.

Aim for one pass over the cells.

  • valid_board(["1..8.2..4","5.4.71.2.",".86..5317","41.237.68","...1..27.","..3..6...","..57.96..",".71...4.5","3...58..."]) → true
  • valid_board(["12.8.2..4","5.4.71.2.",".86..5317","41.237.68","...1..27.","..3..6...","..57.96..",".71...4.5","3...58..."]) → false
  • valid_board(["15.8.2..4","5.4.71.2.",".86..5317","41.237.68","...1..27.","..3..6...","..57.96..",".71...4.5","3...58..."]) → false
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Checking the 27 rows, columns and boxes one at a time works, but one pass is enough: every filled cell belongs to exactly one row, one column and one box.

Hint 2

Turn each fact into a hashable key such as ("row", r, d) and keep them in one set. Name the box (r // 3, c // 3): a single number like r // 3 + c // 3 merges different boxes.

Solution and why it works
pythonO(cells): 81 here · O(cells)
def valid_board(board: list[str]) -> bool:
    seen = set()
    for r, row in enumerate(board):
        for c, d in enumerate(row):
            if d == ".":
                continue
            keys = (("row", r, d), ("col", c, d), ("box", r // 3, c // 3, d))
            if any(k in seen for k in keys):
                return False
            seen.update(keys)
    return True

Each filled cell claims its digit in one row, one column and one box. Storing every claim as a tuple key in a set finds a repeat in O(1), so one pass checks all 27 units at once. The trap is the box id: (r // 3, c // 3) names nine boxes, while r // 3 + c // 3 gives boxes (0, 1) and (1, 0) the same id and reports clashes that don't exist. The board is always 81 cells, so the cost is constant.

Related lab: Loops in motion