Ctrl K

Template in a Digit Grid

Medium
You get a rectangular table grid of digits from 0 to 9 and a rectangular template template, given as a list of strings where every character is either a digit or a lowercase English letter. A rectangular piece of the table with the same size as the template fits it when: - wherever the template has a digit, the piece has exactly that digit; - every letter can be assigned a digit so that each cell under that letter holds its digit; - different letters are assigned different digits. Digits written in the template do not restrict the letters: a letter may stand for a digit that also appears explicitly in the template. Return [row, column] of the top-left corner of a fitting piece. If several fit, pick the one with the smallest row, and on a tie the smallest column. If none fits, return [-1, -1].
Example 1
grid=[[7, 3, 3], [4, 3, 5], [3, 5, 5]], template=["xy", "yz"] → [1, 0]

The window at (0, 0) is 7 3 / 4 3: the letter y sits over both 3 and 4, a contradiction. The window at (0, 1) is 3 3 / 3 5: x and y would both be 3, but different letters must mean different digits. The window at (1, 0) is 4 3 / 3 5: x = 4, y = 3, z = 5, which works.

Example 2
grid=[[2, 8, 8], [5, 1, 8]], template=["8", "8"] → [0, 2]

A template made only of digits needs an exact match: the column 8 / 8 appears only at (0, 2).

Example 3
grid=[[1, 2, 3]], template=["aa"] → [-1, -1]

Two equal neighbouring digits are needed, and there are none.

Constraints
  • 1 ≤ len(grid), len(grid[0]) ≤ 50
  • 0 ≤ grid[i][j] ≤ 9
  • 1 ≤ len(template), len(template[0]) ≤ 50
  • all strings in template have the same length and consist of digits and lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSudoku Board Without Clashes MediumAnagram Buckets MediumZero Out the Crosses MediumWord Traced on a Letter Grid MediumSplit Into Dictionary Words Medium
loading Python…
Input
grid=[[7, 3, 3], [4, 3, 5], [3, 5, 5]], template=["xy", "yz"]
Expected
[1, 0]

Run checks the first 3 tests in your browser. Submit checks all 95 tests on the server, hidden ones included.