Match Cells by Four-Way Gap to Nearest Blocker
Arrays & HashingAuto-graded · 21 test casesLast updated
Compute, for every empty cell, the gap to the nearest blocker in each of four directions using linear sweeps, then return the cells whose four gaps equal a given target.
Four-Way Gap Matching
A warehouse floor is modeled as a rectangular grid. Each cell is either free (0) or blocked (1).
For a free cell, its profile is a list of four gaps, in this fixed order:
[up, down, left, right]
The gap in a direction is defined as follows:
- Walk from the cell in that direction, one step at a time, until you reach a blocked cell.
- The gap is the number of free cells strictly between the starting cell and that first blocked cell. A blocked cell directly next to the start gives a gap of
0. - If you leave the grid without meeting any blocked cell, the gap is
-1. The grid boundary does not count as a blocker.
Given the grid and a target profile of four integers, return the coordinates of every free cell whose profile is exactly equal to the target.
Output format
- Return a list of
[row, column]pairs (each a list of two integers), using 0-based indices. - List the pairs in row-major order: increasing row, and within a row increasing column.
- Blocked cells are never part of the answer.
- If no cell matches, return an empty list.
Constraints
1 <= M, N <= 500, where the grid hasMrows andNcolumns.grid[r][c]is either0(free) or1(blocked).targetcontains exactly 4 integers, in the order[up, down, left, right]. A value of-1means "no blocker in that direction".- A grid with no blocked cells, or one made up entirely of blocked cells, is possible.
Examples
Example 1
Input: find_cells_by_gap_profile([[0, 0, 1], [0, 0, 0], [1, 0, 0]], [2, 1, 1, 0])
Output: []
Hints
Hint 1
Checking each cell by walking outward in four directions is too slow for a 500 x 500 grid. Look for work that can be shared between neighboring cells.
Hint 2
Sweep each column top to bottom while remembering the row of the most recent blocked cell. The up gap of a free cell is then its row minus that row minus one, or -1 if none has been seen yet.
Hint 3
Do the same in the other three directions (bottom to top, left to right, right to left), then make one final pass comparing the four values of each free cell with the target.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walking outward from every free cell in four directions costs O(M·N·(M+N)), which is too slow at 500 x 500. The key observation is that the gap upward from a cell depends only on the most recent blocked cell above it in the same column, so it can be shared between cells.
- Build four matrices
up,down,left,right, all initialized to-1. - Up: for each column, scan top to bottom while keeping
last, the row of the latest blocked cell (or-1if none yet). On a blocked cell, setlast = r. On a free cell withlast != -1, setup[r][c] = r - last - 1. - Down: scan each column bottom to top in the same way, with
down[r][c] = last - r - 1. - Left / Right: do the same along each row, left to right and right to left, using column indices.
- Finally, walk the grid in row-major order and collect every free cell whose four values equal
target.
Why it is correct
While sweeping, last always equals the nearest blocked index before the current position, or -1 if there is none. That blocked cell is the first one met when walking back in that direction, and the free cells strictly between it and the current cell number r - last - 1. If no blocker has been seen, the matrix keeps its -1 default, matching the "no blocker" rule. A blocker at index 0 sets last = 0, which differs from the sentinel -1, so the two cases are never confused. The other three directions are symmetric. A cell is reported exactly when all four values equal the target, and iterating in row-major order gives the required output order. Blocked cells are skipped explicitly.
Complexity
- Time: O(M·N), from four sweeps plus one comparison pass.
- Space: O(M·N) for the four gap matrices (the output can also be that large).
Reference solution
from typing import List
def find_cells_by_gap_profile(grid: List[List[int]], target: List[int]) -> List[List[int]]:
m = len(grid)
n = len(grid[0]) if m else 0
up = [[-1] * n for _ in range(m)]
down = [[-1] * n for _ in range(m)]
left = [[-1] * n for _ in range(m)]
right = [[-1] * n for _ in range(m)]
for c in range(n):
last = -1
for r in range(m):
if grid[r][c] == 1:
last = r
elif last != -1:
up[r][c] = r - last - 1
last = -1
for r in range(m - 1, -1, -1):
if grid[r][c] == 1:
last = r
elif last != -1:
down[r][c] = last - r - 1
for r in range(m):
last = -1
for c in range(n):
if grid[r][c] == 1:
last = c
elif last != -1:
left[r][c] = c - last - 1
last = -1
for c in range(n - 1, -1, -1):
if grid[r][c] == 1:
last = c
elif last != -1:
right[r][c] = last - c - 1
target = list(target)
result = []
for r in range(m):
for c in range(n):
if grid[r][c] == 0 and [up[r][c], down[r][c], left[r][c], right[r][c]] == target:
result.append([r, c])
return result