Check a Partially Filled Number Grid for Rule Violations
Arrays & HashingAuto-graded · 14 test casesLast updated
Scan a 9x9 digit grid once and decide whether any row, column, or 3x3 block repeats a digit, using per-group bitmasks or sets.
You are given a 9x9 grid, grid, representing a partially completed number-placement puzzle. Each cell is a one-character string: either a digit from '1' to '9', or '.' for an empty cell.
Decide whether the grid, as it currently stands, obeys these rules:
- No digit appears more than once in any row.
- No digit appears more than once in any column.
- No digit appears more than once in any of the nine 3x3 blocks. The blocks are formed by splitting the grid into three bands of three rows and three stacks of three columns.
Return True if no rule is broken, and False otherwise.
Details
- Only filled cells are checked. Empty cells (
'.') never cause a violation, and any number of them may repeat. - You are judging only whether the current contents break a rule. You do not need to determine whether the puzzle can be completed. A grid that is rule-abiding but has no possible solution still returns
True. - A grid with no filled cells at all is valid.
- Aim for a single pass over the 81 cells, recording what each row, column and block has already seen, so a conflict is detected the moment the second copy of a digit is encountered.
Constraints
gridhas exactly 9 rows, and each row has exactly 9 entries.- Every entry is one of
'1','2','3','4','5','6','7','8','9', or'.'. - The function returns a boolean.
Examples
Example 1
Input: is_grid_consistent([['5', '3', '.', '.', '7', '.', '.', '.', '.'], ['6', '.', '.', '1', '9', '5', '.', '.', '.'], ['.', '9', '8', '.', '.', '.', '.', '6', '.'], ['8', '.', '.', '.', '6', '.', '.', '.', '3'], ['4', '.', '.', '8', '.', '3', '.', '.', '1'], ['7', '.', '.', '.', '2', '.', '.', '.', '6'], ['.', '6', '.', '.', '.', '.', '2', '8', '.'], ['.', '.', '.', '4', '1', '9', '.', '.', '5'], ['.', '.', '.', '.', '8', '.', '.', '7', '9']])
Output: True
Example 2
Input: is_grid_consistent([['8', '3', '.', '.', '7', '.', '.', '.', '.'], ['6', '.', '.', '1', '9', '5', '.', '.', '.'], ['.', '9', '8', '.', '.', '.', '.', '6', '.'], ['8', '.', '.', '.', '6', '.', '.', '.', '3'], ['4', '.', '.', '8', '.', '3', '.', '.', '1'], ['7', '.', '.', '.', '2', '.', '.', '.', '6'], ['.', '6', '.', '.', '.', '.', '2', '8', '.'], ['.', '.', '.', '4', '1', '9', '.', '.', '5'], ['.', '.', '.', '.', '8', '.', '.', '7', '9']])
Output: False
Hints
Hint 1
Every filled cell belongs to exactly three groups at once: one row, one column and one 3x3 block. Track the digits already seen in each group while scanning.
Hint 2
To map a cell at row r and column c to a block number from 0 to 8, use (r // 3) * 3 + (c // 3).
Hint 3
Represent the seen digits of each group as a 9-bit integer (bit d-1 for digit d) or as a set. Before recording a digit, test whether it is already present in its row, column or block; if so, return False right away.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each filled cell belongs to exactly one row, one column and one 3x3 block. The grid is valid precisely when no digit shows up twice within any of these 27 groups. Instead of checking rows, columns and blocks in separate sweeps, scan the grid once and keep a record of the digits already seen in each group.
Each record is a 9-bit integer: bit k is set when digit k + 1 has already appeared in that group. This gives three arrays of nine integers (rows, cols, blocks).
For every non-empty cell at (r, c):
- Convert the digit to a bit:
bit = 1 << (digit - 1). - Compute the block index:
(r // 3) * 3 + (c // 3). Herer // 3is the band (0 to 2) andc // 3is the stack (0 to 2); combining them numbers the blocks 0 to 8 in reading order. - If
bitis already set in the row, column or block mask, a duplicate exists, so returnFalse. - Otherwise set the bit in all three masks.
If the scan ends without finding a clash, return True.
Why it is correct
- No false rejections: we return
Falseonly when a bit was already set, which means an earlier cell in the same group held the same digit. That is a real violation. - No false acceptances: if two cells share a group and hold the same digit, the earlier one in scan order sets the bit and bits are never cleared, so the later one finds it set and triggers a rejection.
- Empty cells are skipped, so they cannot cause conflicts.
An equivalent version uses set objects per group. Sets are simpler to read and generalize to arbitrary symbols, while bitmasks are more compact and make membership and insertion a single bitwise operation.
Complexity
- Time: 81 cells with constant work each, so O(1) for the fixed 9x9 size (O(N^2) for an N x N board), with an early exit on the first conflict.
- Space: 27 small integers, so O(1).
Reference solution
from typing import List
def is_grid_consistent(grid: List[List[str]]) -> bool:
rows = [0] * 9
cols = [0] * 9
blocks = [0] * 9
for r in range(9):
for c in range(9):
ch = grid[r][c]
if ch == '.':
continue
bit = 1 << (ord(ch) - ord('1'))
b = (r // 3) * 3 + (c // 3)
if rows[r] & bit or cols[c] & bit or blocks[b] & bit:
return False
rows[r] |= bit
cols[c] |= bit
blocks[b] |= bit
return True