← Whiteboard questions

Valid Sudoku

Check a Sudoku board for a repeat in any row, column or box

DSA, Medium, Arrays & Hashing

Which structure or algorithm, and what does it cost.

A Sudoku board is a list of 9 strings, each with 9 characters. A character is a digit from 1 to 9, or a dot for a blank cell. Return true if no digit appears twice in any row, any column or any 3 by 3 box. Ignore blank cells. The board can be unfinished or impossible to finish: you only look for repeats.

Examples

Input board = ["...1.8.6.", "........2", ".......9.", ".....7...", "98....4.1", ".........", "...8.6...", "........9", ".....98.6"]
Output true
Why 16 cells are filled and no digit repeats in any row, column or box.
Input board = ["...1.8.6.", "........2", ".......9.", ".....7...", "98....4.1", ".....8...", "...8.6...", "........9", ".....98.6"]
Output false
Why the new 8 in row 5 repeats the 8 at the top of column 5. Its row and its box are fine, so only the column check catches it.
Input board = ["...1.8.6.", "........2", ".......9.", ".....7...", "98....4.1", ".........", "...8.69..", "........9", ".....98.6"]
Output false
Why the 9 added in row 6 sits in the bottom right box next to another 9. It shares no row and no column with that 9, so only the box check catches it.

Constraints

Your answer must contain

Target Aim for constant work per cell and O(1) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A board is valid when no digit is repeated inside any one of three kinds of groups. Name the three groups.

Hint 2 the approach

You can check all the groups in one walk over the cells. For each filled cell, ask three questions, one for each group it belongs to.

Hint 3 the key step

Keep nine sets each for rows, columns and boxes. How do you turn a row and a column into one box number from 0 to 8?

Walkthrough

Full walkthrough brute force to best

Brute force

For every pair of filled cells, check whether they hold the same digit and share a row, a column or a box. With up to 81 filled cells that is about 3,240 pairs, and each pair costs a few comparisons. It is correct, but it grows as the square of the number of cells, and it needs a careful box test for each pair. The better method is cleaner and grows better.

Better method

Make three passes over the board, one for rows, one for columns and one for boxes. Each pass uses a set per group and stops at a repeat. This is the same cost as one pass and the same memory, but it reads the board three times and repeats code.

Best method

Walk the cells once, row by row. Keep nine sets for the rows, nine for the columns and nine for the boxes. For a filled cell, work out its box number, which is row divided by 3 (whole part) times 3, plus column divided by 3 (whole part). If its digit is already in its row set, its column set or its box set, the board is not valid, so return false. If not, add the digit to all three sets. Empty cells are skipped. If the walk ends, no group had a repeat. The board has a fixed size, so the work is a constant 81 steps. For an n by n board it would be O(n^2).

Hand trace

Run on the first example. Empty cells are skipped. The filled cells in reading order are (row, column, digit, box): (0,3,1,1), (0,5,8,1), (0,7,6,2), (1,8,2,2), (2,7,9,2), (3,5,7,4), (4,0,9,3), (4,1,8,3), (4,6,4,5), (4,8,1,5), (6,3,8,7), (6,5,6,7), (7,8,9,8), (8,5,9,7), (8,6,8,8), (8,8,6,8). Each digit is new in its row set, its column set and its box set when it arrives, so each is added. For example, the 9 at (8,5) finds column 5 holding 8, 7 and 6, and box 7 holding 8 and 6, so it is new. The walk ends and the result is true.

Code

def is_valid_board(board):
    rows = [set() for _ in range(9)]
    cols = [set() for _ in range(9)]
    boxes = [set() for _ in range(9)]
    for r in range(9):
        for c in range(9):
            d = board[r][c]
            if d == '.':
                continue
            b = (r // 3) * 3 + c // 3
            if d in rows[r] or d in cols[c] or d in boxes[b]:
                return False
            rows[r].add(d)
            cols[c].add(d)
            boxes[b].add(d)
    return True

Time and memory

O(1) time for the fixed 9 by 9 board, because there are 81 cells and each needs three set lookups. For an n by n board it is O(n^2). O(1) memory for the 27 sets, which hold at most 81 digits in total.

Common mistakes

  • A wrong box formula, such as row divided by 3 plus column divided by 3. That gives the same number to different boxes. Multiply the row part by 3.
  • Treating the dot as a digit. Then a second empty cell in a row counts as a repeat and every real board fails.
  • Checking rows and columns but not boxes, so a board with a repeat inside one box passes.
  • Asking whether the board can be solved or whether all nine digits are present. The question only asks whether the filled cells break a rule.

Related problems

More Arrays & Hashing problems
Valid Sudoku: hints, walkthrough and Python solution