Locate Symbol-Structure Templates in a Number Grid
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests whether a candidate can slide a letter-template over an integer grid and detect every position where symbols and values form a valid one-to-one correspondence.
Locate Symbol-Structure Templates in a Number Grid
You are given a rectangular grid of integers and a small rectangular template made of uppercase letters. Your task is to find every position in the grid where the template "fits" — meaning the relationship between letters in the template mirrors the relationship between numbers in the corresponding grid window.
What "fits" means
For a given top-left corner (r, c), extract the subgrid of the same height and width as the template. The template fits at (r, c) if and only if there is a one-to-one mapping between the letters in the template and the integers in the subgrid such that:
- Wherever the same letter appears in the template, the exact same integer appears in the subgrid at those positions.
- Wherever two different letters appear, they must correspond to two different integers.
This mapping is local to each candidate window — a letter may map to one integer in one window and a completely different integer in another.
Return a list of [row, col] pairs for every window where the template fits, sorted first by row and then by column.
Constraints
- The grid has between 1 and 50 rows and between 1 and 50 columns.
- The template has between 1 and 5 rows and between 1 and 5 columns.
- Template cells contain only uppercase ASCII letters (
A–Z). - Grid values are integers in the range
[-1,000,000,000, 1,000,000,000]. - The template must fit entirely within the grid; no wrapping or partial overlap is allowed.
- If the template is taller or wider than the grid, return an empty list.
- Do not rotate, reflect, scale, or otherwise transform the template.
Examples
Example 1
Input: locate_template_in_grid([[1, 2, 4, 5], [2, 3, 6, 7], [6, 4, 2, 2]], ['AT', 'TB'])
Output: [[0, 0]]
Example 2
Input: locate_template_in_grid([[7, 7], [7, 7]], ['AA', 'AA'])
Output: [[0, 0]]
Hints
Hint 1
Start by thinking about what makes two grids 'structurally identical': the pattern of equal and unequal values must be the same. This is the same idea as checking whether two strings are isomorphic, extended to two dimensions.
Hint 2
A single forward map (letter → integer) is not enough. Consider the template 'AB' placed over the window [5, 5]: A maps to 5 and B maps to 5 without any forward-map conflict, yet A and B are different letters and must map to different integers. You need a second reverse map (integer → letter) to catch this case.
Hint 3
For each candidate window, build both maps from scratch. Scan cells in row-major order. At each cell, check both maps before writing to them: if a letter already has a different integer, or an integer already belongs to a different letter, reject the window immediately and move to the next.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the 2-D generalisation of the classic "isomorphic strings" problem. Slide a window the same size as the template over every valid top-left position in the grid. For each window, decide whether a bijection (a one-to-one and onto mapping) exists between the template's letters and the window's integers.
Two hash maps are used to enforce both directions of the bijection simultaneously:
letter_to_int— guarantees that the same letter always resolves to the same integer within this window.int_to_letter— guarantees that the same integer is never claimed by two different letters within this window.
Both maps are created fresh for each candidate window, because the mapping is allowed to be completely different from one window to the next. Cells are visited in row-major order. At the first conflict in either map, the window is rejected immediately and the inner loops exit early.
Why both maps are necessary
A single forward map is not sufficient. Consider the template "AB" placed over the window [5, 5]. The forward map records A → 5 and then B → 5 without seeing any repeated letter, so it would (wrongly) accept. The reverse map catches it: when B tries to claim 5, the map already records 5 → A, which is a different letter — conflict, reject.
Why this is correct
A window is accepted only when every cell passes both checks. At that point:
- The forward map is well-defined (each letter has exactly one integer).
- The forward map is injective (no two letters share an integer, enforced by the reverse map).
Together these mean the mapping is a valid bijection, so accepting is correct. Conversely, any true conflict causes an early exit, so no false positives are produced.
Results are appended in the order the loops run — outer loop over rows, inner loop over columns — so the output is automatically sorted by row then by column.
Complexity
Let the grid be R × C and the template T_h × T_w.
- Time: O((R − T_h + 1)(C − T_w + 1) · T_h · T_w). With the given constraints this is at most 2 500 windows × 25 cells = 62 500 cell checks. Early exit on the first conflict makes the average case much faster.
- Space: O(T_h · T_w) for the two maps per window. Each map holds at most 26 entries (one per letter), so in practice this is O(1). The output list can hold at most O(R · C) coordinates.
Edge cases
- Template larger than the grid in either dimension: no window fits; return
[]. - 1 × 1 template: every cell is trivially a match; return all R · C positions.
- All-same-letter template (e.g.,
["AA","AA"]): matches only windows where every value is identical. - All-distinct-letter template: matches only windows where every value is distinct.
- Two different letters, same integer (e.g.,
"AB"over[5, 5]): must be rejected — the reverse map handles this. - Negative and very large integers: dictionary keys work for any integer, so no special handling is needed.
Full solution
from typing import List
def locate_template_in_grid(grid: List[List[int]], template: List[str]) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0]) if rows else 0
th = len(template)
tw = len(template[0]) if th else 0
result = []
# Template cannot fit if it is larger than the grid in either dimension.
if not rows or not cols or not th or not tw or th > rows or tw > cols:
return result
for r in range(rows - th + 1):
for c in range(cols - tw + 1):
# Both maps are reset for every candidate window.
letter_to_int = {}
int_to_letter = {}
matched = True
for i in range(th):
for j in range(tw):
letter = template[i][j]
value = grid[r + i][c + j]
# Same letter must always map to the same integer.
if letter in letter_to_int and letter_to_int[letter] != value:
matched = False
break
# Same integer must not be claimed by two different letters.
if value in int_to_letter and int_to_letter[value] != letter:
matched = False
break
letter_to_int[letter] = value
int_to_letter[value] = letter
if not matched:
break
if matched:
result.append([r, c])
return result
Alternative worth knowing
You can normalise each sequence to a canonical form by replacing every element with the index of its first appearance in row-major order. For example, both AT/TB and the subgrid 1,2/2,3 normalise to [0,1,1,2]. A window matches exactly when its canonical sequence equals the template's pre-computed canonical sequence.
This is logically equivalent to the two-map approach and lets you precompute the template form once. The trade-off is that you lose the early-exit benefit unless you compare element by element while building the canonical form. The two-map approach is generally easier to explain and defend in an interview setting.