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:
- Row uniqueness: In each of the 9 horizontal rows (
0..8), every placed digit"1"–"9"appears at most once. - Column uniqueness: In each of the 9 vertical columns (
0..8), every placed digit"1"–"9"appears at most once. - Subgrid uniqueness: Partitioning rows into
{0..2},{3..5},{6..8}and columns into{0..2},{3..5},{6..8}defines nine non-overlapping3 x 3subgrids; within each3 x 3subgrid, 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 3subgrid, returnTrueeven 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) == 9andlen(board[r]) == 9for every0 <= 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
Understand what "valid" means here
We are given a
9 x 9grid of single-character strings:"1"through"9"for filled squares, and"."for empty squares. We must returnTrueif and only if no filled digit appears more than once in:- the same row (
0..8), - the same column (
0..8), or - the same
3 x 3box (nine non-overlapping3 x 3blocks).
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
Trueas long as no existing digits conflict right now.
- the same row (
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 a3 x 3box. With at most81cells (81 * 80 / 2 = 3,240pairs), that finishes quickly on9 x 9, but on anN x Nboard it scales poorly atO(N^4).Instead, we can scan each cell once by maintaining 27 hash sets (a Python
setstores unique items and checksx in sinO(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.
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 number0..8?Integer division by
3(// 3) collapses three consecutive indices into one block coordinate:0, 1, 2 -> 0,3, 4, 5 -> 1, and6, 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
bandby3inband * 3 + stack? Without* 3,(row=0, col=3)in Box1and(row=3, col=0)in Box3would both compute0 + 1 == 1 + 0 == 1and collide! Multiplyingband * 3steps by3boxes per horizontal band, just like flattening a3 x 3grid into row-major indices0..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 + stackBuild 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()] * 9creates one single set and puts 9 references to that exact same set into the list, so adding"5"to row0makes"5"appear in every row! Instead, append a freshset()on each iteration of aforloop.Then, as we visit each
(row, col):- If
cell == ".",continueimmediately so empty dots are never stored in any set. - Check whether
cellis already inrows_seen[row],cols_seen[col], orboxes_seen[box]. If so, returnFalseright away. - Only after passing all three checks, add
cellto 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- If
Trace Example 2 on the center `3 x 3` box
In Example 2, look at the filled cells that land inside Box
4(rows3..5, cols3..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 immediatelyNotice that row
4and column4had not seen"6"yet, so onlyboxes_seen[4]catches this violation. In Example 1,(3, 5)is"."instead of"6", so all 81 cells pass and the function returnsTrue.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 9board (O(N^2)for anN x Nboard). The nested loop visits at most9 * 9 = 81cells once, performing integer division plus at most 3O(1)average set lookups and 3O(1)average set insertions per cell. - Space: O(1) for a fixed
9 x 9board (O(N^2)for anN x Nboard). The 27 sets hold at most9digit strings each (<= 243total entries across all sets).
Edge cases
- Completely empty board (all
"."): Every cell triggersif cell == ".": continue, so the sets stay empty and the function returnsTrue. - Completely solved
9 x 9board: Every unit fills up with{"1".."9"}without a single repeat and returnsTrue. - Same digit across non-overlapping units: Digits at
(0, 0)and(1, 3)sit in different rows (0vs1), different columns (0vs3), and different boxes (0vs1), so both are valid. - Diagonal boundary between boxes:
(2, 2)hasbox_index = 0whereas(3, 3)hasbox_index = 4, so identical digits there are valid; meanwhile(0, 0)and(2, 2)both map tobox_index = 0and conflict. - Symmetric off-diagonal boxes:
(0, 3)maps to0 * 3 + 1 = 1(top-middle box) while(3, 0)maps to1 * 3 + 0 = 3(middle-left box), so they do not falsely collide. - Consistent yet unsolvable board: Suppose row
0holds"1"through"8"in columns0..7(leaving(0, 8)needing"9"), while(1, 8)already holds"9". No row, column, or box currently repeats a digit, sois_valid_boardmust returnTrue.
Common mistakes
- Initializing sets with
[set()] * 9: List multiplication copies references to the same underlyingsetobject 9 times, making a digit placed in row0appear in rows1..8simultaneously! Always create 9 distinct sets in a loop or list comprehension. - Forgetting
* 3in the box formula (row // 3 + col // 3): Addition is symmetric, so(0, 3)in Box1and(3, 0)in Box3both evaluate to1, 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 returnsFalse. - Inserting before checking membership: Calling
rows_seen[row].add(cell)beforeif cell in rows_seen[row]:guaranteescellis 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 = 4on a16 x 16Hexadoku grid), createNsets each forrows_seen,cols_seen, andboxes_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 inO(N^2)time andO(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 (
0or1) act as compact boolean flags for digits1..9. Store three 9-element integer lists initialized to0(rows_mask,cols_mask,boxes_mask); for each filledcell, computebit = 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, andboxes_seentrackers 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 returnsFalse.
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?
- Can you replace the 27 hash sets with integer bitmasks to cut memory allocations?
- What changes are needed if we want to solve the puzzle rather than only checking current consistency?
Similar questions
- Backward File Tailer and Heartbeat Monitor
- Streaming File Tail and Minimum-Monster Dungeon Path
- Read the Last N Lines
- Resolve Calls Against Fixed and Variadic Signatures
- Pod Counter Management with Broadcast Increments
- Pairwise Majority Song Ranking
More Confluent interview questions
- Indexed Whole-Word and Sequential Phrase Search Over Documents Medium
- Resolve Calls Against Fixed and Variadic Signatures Medium
- Verify and Lexicographically Solve a 9x9 Sudoku Grid Medium Pro
- Backward Chunked Reader for Trailing File Lines Medium Pro
- News Aggregator and Disposable Inbox Platform Medium Pro
- Scalable Podcast Ingestion and Subscriber Feed Medium Pro
- LRU Cache Supporting O(1) Running Mean Medium Pro
- In-Memory Document Search with Phrase and Boolean Queries Medium Pro
- Linux Process Execution, Filesystem Internals, and Container Isolation Medium Pro
- Variadic Functions and Typesafe Structured Logging Hard Pro