Validate Consistency of a Partial 9x9 Sudoku Grid

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Given an in-progress 9 x 9 Sudoku grid board containing digit characters "1"–"9" and "." placeholders for blank squares, check whether the currently placed digits obey every Sudoku uniqueness constraint.

def is_valid_board(board: list[list[str]]) -> bool:

Return True precisely when all three conditions hold across the filled squares, and False otherwise:

  1. Row uniqueness: In each of the 9 horizontal rows (0..8), every placed digit "1"–"9" appears at most once.
  2. Column uniqueness: In each of the 9 vertical columns (0..8), every placed digit "1"–"9" appears at most once.
  3. Subgrid uniqueness: Partitioning rows into {0..2}, {3..5}, {6..8} and columns into {0..2}, {3..5}, {6..8} defines nine non-overlapping 3 x 3 subgrids; within each 3 x 3 subgrid, every placed digit "1"–"9" appears at most once.

Important clarifications:

  • Blank "." entries are ignored and never count as duplicates.
  • Evaluate current consistency only, not whether the grid can eventually be completed into a finished Sudoku solution. If no placed digit repeats in any row, column, or 3 x 3 subgrid, return True even if no valid full assignment exists for the remaining "." squares.

Examples

Example 1

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

Every horizontal row, vertical column, and 3 x 3 subgrid contains three distinct digits with zero collisions.

Example 2

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

Placing "6" at (3, 5) creates no conflict along row 3 or column 5, yet the central 3 x 3 subgrid (rows 3..5, cols 3..5) now contains "6" at both (3, 5) and (4, 4), violating subgrid uniqueness.

Constraints

  • len(board) == 9 and len(board[r]) == 9 for every 0 <= r < 9.
  • Each entry board[r][c] is a single-character string in {"1", "2", "3", "4", "5", "6", "7", "8", "9", "."}.

Step-by-step walkthrough

  1. Understand what "valid" means here

    We are given a 9 x 9 grid of single-character strings: "1" through "9" for filled squares, and "." for empty squares. We must return True if and only if no filled digit appears more than once in:

    1. the same row (0..8),
    2. the same column (0..8), or
    3. the same 3 x 3 box (nine non-overlapping 3 x 3 blocks).

    Two crucial boundaries prevent overcomplicating the problem:

    • Empty "." cells are completely ignored. A row with nine "." characters is valid.
    • Consistency is not solvability. We never guess digits or run search/backtracking. Even if the filled digits leave some empty square with zero legal choices later on, the board is still True as long as no existing digits conflict right now.
  2. Compare every pair vs. a single pass with sets

    A brute-force check collects all filled cells (r, c, digit) and compares every pair (i, j) to see whether two identical digits share a row, a column, or a 3 x 3 box. With at most 81 cells (81 * 80 / 2 = 3,240 pairs), that finishes quickly on 9 x 9, but on an N x N board it scales poorly at O(N^4).

    Instead, we can scan each cell once by maintaining 27 hash sets (a Python set stores unique items and checks x in s in O(1) average time):

    • rows_seen[0..8]: digits seen so far in each of the 9 rows,
    • cols_seen[0..8]: digits seen so far in each of the 9 columns,
    • boxes_seen[0..8]: digits seen so far in each of the 9 boxes.
  3. Map `(row, col)` to its `3 x 3` box ID `0..8`

    Rows and columns already have indices 0..8. How do we turn (row, col) into a unique box number 0..8?

    Integer division by 3 (// 3) collapses three consecutive indices into one block coordinate: 0, 1, 2 -> 0, 3, 4, 5 -> 1, and 6, 7, 8 -> 2:

                  col 0..2        col 3..5        col 6..8
                 (stack = 0)     (stack = 1)     (stack = 2)
                +---------------+---------------+---------------+
    row 0..2    |               |               |               |
    (band = 0)  |    Box 0      |    Box 1      |    Box 2      |
                |  0*3 + 0 = 0  |  0*3 + 1 = 1  |  0*3 + 2 = 2  |
                +---------------+---------------+---------------+
    row 3..5    |               |               |               |
    (band = 1)  |    Box 3      |    Box 4      |    Box 5      |
                |  1*3 + 0 = 3  |  1*3 + 1 = 4  |  1*3 + 2 = 5  |
                +---------------+---------------+---------------+
    row 6..8    |               |               |               |
    (band = 2)  |    Box 6      |    Box 7      |    Box 8      |
                |  2*3 + 0 = 6  |  2*3 + 1 = 7  |  2*3 + 2 = 8  |
                +---------------+---------------+---------------+
    

    Why multiply band by 3 in band * 3 + stack? Without * 3, (row=0, col=3) in Box 1 and (row=3, col=0) in Box 3 would both compute 0 + 1 == 1 + 0 == 1 and collide! Multiplying band * 3 steps by 3 boxes per horizontal band, just like flattening a 3 x 3 grid into row-major indices 0..8.

    def box_index(row: int, col: int) -> int:
        # Integer division groups rows 0..8 into 3 horizontal bands (0, 1, 2)
        # and cols 0..8 into 3 vertical stacks (0, 1, 2).
        band = row // 3
        stack = col // 3
        # Multiply `band` by 3 so each row of 3x3 boxes gets a distinct ID in 0..8.
        return band * 3 + stack
    
  4. Build the 27 sets safely and scan cell by cell

    Watch out for a classic Python pitfall when creating lists of mutable sets: writing rows_seen = [set()] * 9 creates one single set and puts 9 references to that exact same set into the list, so adding "5" to row 0 makes "5" appear in every row! Instead, append a fresh set() on each iteration of a for loop.

    Then, as we visit each (row, col):

    1. If cell == ".", continue immediately so empty dots are never stored in any set.
    2. Check whether cell is already in rows_seen[row], cols_seen[col], or boxes_seen[box]. If so, return False right away.
    3. Only after passing all three checks, add cell to all three sets.
    def is_valid_board(board: list[list[str]]) -> bool:
        rows_seen: List[Set[str]] = []
        cols_seen: List[Set[str]] = []
        boxes_seen: List[Set[str]] = []
        for _ in range(9):
            rows_seen.append(set())
            cols_seen.append(set())
            boxes_seen.append(set())
    
        for row in range(9):
            for col in range(9):
                cell = board[row][col]
                if cell == ".":
                    continue
    
                box = box_index(row, col)
                if (
                    cell in rows_seen[row]
                    or cell in cols_seen[col]
                    or cell in boxes_seen[box]
                ):
                    return False
    
                rows_seen[row].add(cell)
                cols_seen[col].add(cell)
                boxes_seen[box].add(cell)
    
        return True
    
  5. Trace Example 2 on the center `3 x 3` box

    In Example 2, look at the filled cells that land inside Box 4 (rows 3..5, cols 3..5):

    Cell      Digit  band, stack -> box   Check sets before add             Sets after add (Box 4)
    --------  -----  -------------------  --------------------------------  ----------------------
    (3, 3)     "4"    1, 1 -> Box 4       not in row 3, col 3, or box 4     boxes_seen[4] = {"4"}
    (3, 5)     "6"    1, 1 -> Box 4       not in row 3, col 5, or box 4     boxes_seen[4] = {"4", "6"}
    (4, 4)     "6"    1, 1 -> Box 4       row 4 ok, col 4 ok,
                                          "6" IN boxes_seen[4] -> CONFLICT! return False immediately
    

    Notice that row 4 and column 4 had not seen "6" yet, so only boxes_seen[4] catches this violation. In Example 1, (3, 5) is "." instead of "6", so all 81 cells pass and the function returns True.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def box_index(row: int, col: int) -> int:
        # Integer division groups rows 0..8 into 3 horizontal bands (0, 1, 2)
        # and cols 0..8 into 3 vertical stacks (0, 1, 2).
        band = row // 3
        stack = col // 3
        # Multiply `band` by 3 so each row of 3x3 boxes gets a distinct ID in 0..8.
        return band * 3 + stack
    
    
    def is_valid_board(board: list[list[str]]) -> bool:
        # Track seen digits ("1".."9") independently for each row, column, and 3x3 box.
        # Example: rows_seen[0] = {"2", "5", "1"} means row 0 has seen those digits so far.
        # Build 9 separate sets in a loop (`[set()] * 9` would share one set across all 9 slots!).
        rows_seen: List[Set[str]] = []
        cols_seen: List[Set[str]] = []
        boxes_seen: List[Set[str]] = []
        for _ in range(9):
            rows_seen.append(set())
            cols_seen.append(set())
            boxes_seen.append(set())
    
        for row in range(9):
            for col in range(9):
                cell = board[row][col]
                # Empty cells "." never violate Sudoku rules; skip them before touching any set.
                if cell == ".":
                    continue
    
                box = box_index(row, col)
    
                # Check all three units BEFORE inserting `cell`, otherwise `cell` would
                # immediately match itself as a false duplicate.
                if (
                    cell in rows_seen[row]
                    or cell in cols_seen[col]
                    or cell in boxes_seen[box]
                ):
                    return False
    
                rows_seen[row].add(cell)
                cols_seen[col].add(cell)
                boxes_seen[box].add(cell)
    
        return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture 27 referees watching the Sudoku grid at the same time — 9 row referees, 9 column referees, and 9 3 x 3-box referees — where each referee holds a small checklist (a hash set, Python's set, which checks membership and records an item in O(1) average time). As we read across the grid square by square, we skip empty "." squares, and for each filled digit we ask the three referees responsible for that square (row, col, and box): "Have any of you already checked off this digit?" If any of the three says yes, we blow the whistle (return False) immediately; otherwise all three check off that digit and we move to the next square.

Why do other instincts lead people astray? Checking every pair of filled squares against each other repeats work across the board (O(N^4) on a generalized N x N grid), while writing three separate nested loop structures (one for rows, one for columns, and a fiddly 4-nested loop for 3 x 3 boxes) triples the code and invites indexing typos. Worse, trying to solve the board with search/backtracking takes exponential time and returns the wrong answer (False instead of True) when a partially filled board has no duplicate digits today yet turns out to have no full completion later!

Here is a 3-cell trace inside the center 3 x 3 box (box = (row // 3) * 3 + (col // 3) = 4) from Example 2:

1. (3, 3) = "4" -> row 3: {"1","4"},     col 3: {"8","4"}, box 4: {"4"}
2. (3, 5) = "6" -> row 3: {"1","4","6"}, col 5: {"5","6"}, box 4: {"4","6"}
3. (4, 4) = "6" -> row 4 has {"7"}, col 4 has {"2"}, BUT box 4 already has "6" -> return False!

Complexity

  • Time: O(1) for a fixed 9 x 9 board (O(N^2) for an N x N board). The nested loop visits at most 9 * 9 = 81 cells once, performing integer division plus at most 3 O(1) average set lookups and 3 O(1) average set insertions per cell.
  • Space: O(1) for a fixed 9 x 9 board (O(N^2) for an N x N board). The 27 sets hold at most 9 digit strings each (<= 243 total entries across all sets).

Edge cases

  • Completely empty board (all "."): Every cell triggers if cell == ".": continue, so the sets stay empty and the function returns True.
  • Completely solved 9 x 9 board: Every unit fills up with {"1".."9"} without a single repeat and returns True.
  • Same digit across non-overlapping units: Digits at (0, 0) and (1, 3) sit in different rows (0 vs 1), different columns (0 vs 3), and different boxes (0 vs 1), so both are valid.
  • Diagonal boundary between boxes: (2, 2) has box_index = 0 whereas (3, 3) has box_index = 4, so identical digits there are valid; meanwhile (0, 0) and (2, 2) both map to box_index = 0 and conflict.
  • Symmetric off-diagonal boxes: (0, 3) maps to 0 * 3 + 1 = 1 (top-middle box) while (3, 0) maps to 1 * 3 + 0 = 3 (middle-left box), so they do not falsely collide.
  • Consistent yet unsolvable board: Suppose row 0 holds "1" through "8" in columns 0..7 (leaving (0, 8) needing "9"), while (1, 8) already holds "9". No row, column, or box currently repeats a digit, so is_valid_board must return True.

Common mistakes

  • Initializing sets with [set()] * 9: List multiplication copies references to the same underlying set object 9 times, making a digit placed in row 0 appear in rows 1..8 simultaneously! Always create 9 distinct sets in a loop or list comprehension.
  • Forgetting * 3 in the box formula (row // 3 + col // 3): Addition is symmetric, so (0, 3) in Box 1 and (3, 0) in Box 3 both evaluate to 1, causing false-negative rejections on valid boards.
  • Forgetting to skip ".": Inserting "." into sets treats the second empty cell in any row, column, or box as a duplicate "." and returns False.
  • Inserting before checking membership: Calling rows_seen[row].add(cell) before if cell in rows_seen[row]: guarantees cell is found immediately, rejecting every board that has at least one digit.
  • Running a Sudoku solver: Backtracking checks solvability rather than current consistency, which both wastes time and fails valid-but-unsolvable test cases.

Follow-up questions

  • How would you adapt this check to an N x N Sudoku variant partitioned into k x k subgrids where N = k^2? Compute k = math.isqrt(N) (for example, k = 4 on a 16 x 16 Hexadoku grid), create N sets each for rows_seen, cols_seen, and boxes_seen, and change the box formula to (row // k) * k + (col // k). Because Python sets accept arbitrary strings ("10", "A", etc.), the cell-checking loop works unchanged in O(N^2) time and O(N^2) space.
  • Can you replace the 27 hash sets with integer bitmasks to cut memory allocations? Yes: use a bitmask — an integer whose individual binary bits (0 or 1) act as compact boolean flags for digits 1..9. Store three 9-element integer lists initialized to 0 (rows_mask, cols_mask, boxes_mask); for each filled cell, compute bit = 1 << (int(cell) - 1), check for a duplicate with bitwise AND ((rows_mask[row] & bit) or (cols_mask[col] & bit) or (boxes_mask[box] & bit)), and record the digit with bitwise OR (rows_mask[row] |= bit).
  • What changes are needed if we want to solve the puzzle rather than only checking current consistency? Keep the exact same rows_seen, cols_seen, and boxes_seen trackers and wrap them in backtracking (a recursive trial-and-error search that places a tentative choice, explores forward, and undoes the choice whenever it hits a dead end). At each step, pick an empty cell—ideally the one with the fewest remaining legal candidates ("1".."9" not in its row, column, or box sets)—add a candidate digit to all three sets, recurse, and remove it from all three sets if the recursive call returns False.

Follow-up questions

Similar questions

More Confluent interview questions

All 30 Confluent questions →