Grid Sentinels: Match Robots by Barrier Distance Profile
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests efficient 2-D prefix sweeps to compute each robot's nearest-wall distance in four directions and filter by an exact profile query.
Grid Sentinels: Match Robots by Barrier Distance Profile
You are given a rectangular grid and a four-element profile. Each cell in the grid is one of three things: a robot ('R'), a barrier ('#'), or an open cell ('.'). For every robot, you can measure how far it sits from the nearest barrier in each cardinal direction — treating the boundary of the grid itself as a barrier.
Your task: return the [row, col] position of every robot whose four-directional barrier distances match the profile exactly.
Distance rules
Label the grid rows 0 to m-1 (top to bottom) and columns 0 to n-1 (left to right).
For a robot at position (r, c), define:
| Direction | Value |
|---|---|
dist_up | r - i, where i is the largest row index satisfying i < r and grid[i][c] == '#'; use i = -1 if no such row exists |
dist_down | i - r, where i is the smallest row index satisfying i > r and grid[i][c] == '#'; use i = m if no such row exists |
dist_left | c - j, where j is the largest column index satisfying j < c and grid[r][j] == '#'; use j = -1 if no such column exists |
dist_right | j - c, where j is the smallest column index satisfying j > c and grid[r][j] == '#'; use j = n if no such column exists |
A few things to note:
- Only
'#'cells act as barriers. Other robots and open cells are transparent — the sweep continues through them as if they were not there. - A robot sitting immediately beside a barrier (or beside the grid edge) has distance
1in that direction, so every distance is at least1.
Profile matching
The query profile is [up, down, left, right]. A robot matches when all four of its distances equal the corresponding profile values simultaneously.
Return every matching robot's position as [row, col], sorted first by row and then by column within the same row. Return an empty list when no robot matches.
Constraints
1 <= m <= 500and1 <= n <= 500, wherem = len(grid)andn = len(grid[0])- All rows have the same length
- Every character in
gridis'R','#', or'.' len(profile) == 41 <= profile[k] <= 10^9for everyk
Examples
Example 1
Input: locate_matching_robots(['R.#.R', '.R...', '#.R.R'], [2, 2, 2, 4])
Output: [[1, 1]]
Example 2
Input: locate_matching_robots(['R#R.', '....', 'R#R#'], [3, 1, 1, 1])
Output: [[2, 0], [2, 2]]
Example 3
Input: locate_matching_robots(['R'], [1, 1, 1, 2])
Output: []
Hints
Hint 1
A brute force that scans outward from each robot in all four directions costs O(m·n·(m+n)) in the worst case — think about how a single pass over the grid could give you the distance for every cell at once.
Hint 2
Process each column top-to-bottom while tracking the row of the most recent '#' seen (use -1 as a sentinel for the top edge). The same idea with reversed traversal and the sentinel m handles the downward distances. Then apply the same logic row-by-row for left and right.
Hint 3
Only '#' should update your tracker. If you also update on 'R', robots in the line of sight will incorrectly block the sweep — verify with a case where two robots share a column with no barrier between them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why a naive scan is too slow
The obvious approach — for each robot, walk outward in all four directions until hitting a barrier or edge — takes up to O(m + n) per robot. With a 500×500 grid full of robots, that's roughly 250 million steps, which is too slow for a time-limited judge.
Directional sweeps
The key insight is that every cell's distance in a given direction can be computed in a single linear pass, because the answer at position r depends only on where the most recent barrier was seen so far.
Upward distances — sweep each column from top to bottom. Maintain last[c], the row of the most recent '#' in column c. Initialize to -1, which acts as the virtual top-edge barrier. For any non-barrier cell at row r, dist_up = r - last[c]. Update last[c] = r only when the cell is '#'.
Downward distances — same sweep in reverse (bottom to top). Initialize last[c] = m, the virtual bottom-edge barrier.
Leftward and rightward distances — because these depend only on the current row, recompute them during the final pass. Sweep left-to-right with lb = -1 for the left edge, and right-to-left with rb = n for the right edge.
After the sweeps, one final row-major pass checks every 'R' cell against the profile. Because this pass goes top-to-bottom and left-to-right, the output is already sorted — no extra sort needed.
Why it is correct
By induction, when the top-to-bottom sweep reaches row r in column c, last[c] holds exactly the largest row index i < r with a '#' at (i, c), or -1 if none exists. This matches the definition of dist_up verbatim. The three other sweeps follow the same argument with their respective sentinels (m, -1, n).
The critical detail: last is updated only on '#'. Skipping 'R' and '.' cells is what lets the sweep "see through" other robots, which is exactly what the problem requires.
Large query values (up to 10⁹) can never match, because every distance is at most max(m, n) + 1 ≤ 501. The equality check handles this automatically — no special case is needed.
Complexity
- Time:
O(m·n)— four sweeps, each visiting every cell once, plus one final pass. - Space:
O(m·n)for theupanddownmatrices. Theleftandrightarrays are rebuilt per row, so they contribute onlyO(n). Output can be at mostm·npairs.
Edge cases
- Grid edges as barriers: the sentinels
-1,m, andncover this without any branching. - Robots in the line of sight: ignored by design — only
'#'updates the tracker. - Profile values larger than the grid: impossible to match; the equality check rejects them silently.
- No robots / all robots: both work correctly in
O(m·n). - 1×1 grid with a single robot: distances are
[1, 1, 1, 1]in all directions.
Reference solution
from typing import List
def locate_matching_robots(grid: List[str], profile: List[int]) -> List[List[int]]:
m, n = len(grid), len(grid[0])
# --- upward distances (top-to-bottom sweep per column) ---
up = [[0] * n for _ in range(m)]
last = [-1] * n # sentinel: -1 represents the top edge
for r in range(m):
row = grid[r]
for c in range(n):
if row[c] == '#':
last[c] = r
else:
up[r][c] = r - last[c]
# --- downward distances (bottom-to-top sweep per column) ---
down = [[0] * n for _ in range(m)]
last = [m] * n # sentinel: m represents the bottom edge
for r in range(m - 1, -1, -1):
row = grid[r]
for c in range(n):
if row[c] == '#':
last[c] = r
else:
down[r][c] = last[c] - r
p_up, p_down, p_left, p_right = profile
result = []
for r in range(m):
row = grid[r]
# --- leftward distances (left-to-right sweep within this row) ---
left = [0] * n
lb = -1 # sentinel: -1 represents the left edge
for c in range(n):
if row[c] == '#':
lb = c
else:
left[c] = c - lb
# --- rightward distances (right-to-left sweep within this row) ---
right = [0] * n
rb = n # sentinel: n represents the right edge
for c in range(n - 1, -1, -1):
if row[c] == '#':
rb = c
else:
right[c] = rb - c
# Row-major iteration already produces output sorted by (row, col).
for c in range(n):
if (row[c] == 'R'
and up[r][c] == p_up
and down[r][c] == p_down
and left[c] == p_left
and right[c] == p_right):
result.append([r, c])
return result