Problem 305059 · medium · Level 03 Linear Management & Searching

Check a Partially Filled Number Grid

matrix · sets · index arithmetic

A puzzle grid is given as a list of nine strings, each nine characters long. Every character is a digit 1-9 or a . for an empty cell. The grid is consistent when no digit repeats within any row, within any column, or within any of the nine 3 x 3 blocks (rows 0-2, 3-5, 6-8 crossed with the same column bands). Return True if the grid is consistent and False otherwise. Empty cells impose no constraint; the puzzle does not need to be solvable or complete.

Examples

Input:  grid = ["5.4.7.9.2", ".7.1.5.4.", "1.8.4.5.7", ".5.7.1.2.", "4.6.5.7.1",
                ".1.9.4.5.", "9.1.3.2.4", ".8.4.9.3.", "3.5.8.1.9"]
Output: True

Input:  grid = ["1........", "..1......", ".........", ".........", ".........",
                ".........", ".........", ".........", "........."]
Output: False
Explanation: the two 1s sit in different rows and columns but in the same top-left block.

Constraints

  • The grid is always 9 x 9.
  • Target: O(81) time, i.e. a single pass over the cells.

Goals

  • Track seen values per row, per column and per block in one pass
  • Map a cell to its 3 x 3 block index with integer division
  • Ignore blank cells while still validating the rest
Starting Python…