Reduce Worst-Case Coverage Gap with One New Relay Node
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests binary search on answer combined with multi-source BFS and 2D prefix sums to optimally place one relay node and minimize the maximum Chebyshev coverage distance.
You are given a rectangular grid of 0s and 1s. Each 1 is an existing relay node. Each 0 is an uncovered cell. The distance between any two cells (r1, c1) and (r2, c2) is the Chebyshev distance: max(abs(r1 - r2), abs(c1 - c2)).
The coverage gap of the grid is the largest Chebyshev distance from any uncovered cell to its nearest relay node.
You may promote at most one uncovered cell into a relay node. Return the smallest possible coverage gap after this optional promotion.
Notes
- An uncovered cell promoted to a relay node is no longer considered uncovered, so it does not contribute to the coverage gap.
- Adding a relay node never removes or repositions existing ones.
- If every cell is already a relay node (no uncovered cells remain), the coverage gap is
0by convention. - You are not required to add a node; if the existing layout is already optimal, return its current gap.
- The grid may contain no relay nodes at all. In that case you must place exactly one to make the gap well-defined.
- There are no obstacles; distance is purely coordinate-based.
Constraints
1 <= rows <= 5001 <= cols <= 500- Every cell value is
0or1 - The grid is guaranteed to have at least one cell
Examples
Example 1
Input: min_coverage_gap([[0, 0, 0, 1], [0, 0, 0, 1]])
Output: 1
Example 2
Input: min_coverage_gap([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Output: 2
Hints
Hint 1
Binary-search on the answer: for each candidate gap value L, ask only whether it is achievable. This reduces the problem to a yes/no feasibility check run O(log(max(rows, cols))) times.
Hint 2
For a fixed L, an uncovered cell is 'already fine' if it sits within Chebyshev distance L of some existing relay node. Run multi-source BFS with 8-directional steps from all relay nodes at once — BFS depth equals Chebyshev distance exactly. Any cell not yet fine needs the new node to cover it, which means the new node must lie in a square of side 2L+1 centered on that cell. The valid placement zon…
Hint 3
The intersection rectangle shrinks as you scan bad cells; if it ever becomes empty, immediately return False. Otherwise check whether the rectangle contains at least one uncovered cell using a 2D prefix-sum table built once before the binary search.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Framing the problem
Rather than trying every possible cell placement directly, notice that the answer has a clean monotone property: if a coverage gap of L is achievable, then so is any gap larger than L. This makes the answer a perfect target for binary search. The search range is [0, max(rows-1, cols-1)], and for each candidate L we only need to answer: "Can we place one new relay node so that every uncovered cell is within Chebyshev distance L of some relay?"
Multi-source BFS for Chebyshev distance
The key geometric fact is that 8-directional BFS depth equals Chebyshev distance. A diagonal step changes both coordinates by 1, costing one unit under max(|Δr|, |Δc|), just like an axis-aligned step does. So launching BFS simultaneously from every existing relay node (multi-source BFS) fills the distance grid in one pass of O(R·C).
The feasibility check
Fix a limit L. An uncovered cell (r, c) is already satisfied if dist[r][c] <= L. Any remaining bad cell requires the new relay node to sit within its Chebyshev square [r-L, r+L] × [c-L, c+L]. The set of valid placements is the intersection of all those squares, which is itself an axis-aligned rectangle. The intersection shrinks monotonically as we scan bad cells; if it ever becomes empty we can return False immediately.
If the intersection is non-empty at the end, we just need it to contain at least one uncovered cell (since only a 0 cell can be promoted). A 2D prefix sum over the zeros answers any rectangle count query in O(1), built once before the binary search loop.
Why this is correct
- A
1cell inside the intersection would already be a relay, meaning every bad cell is withinLof it — contradicting those cells being bad. So thehas_uncoveredcheck is both necessary and sufficient. - If no bad cells exist for a given
L, the existing arrangement already achieves it and no promotion is needed. - With no relays at all, every uncovered cell is bad for every
L, so the check degenerates to "is there a0withinLof all cells?", which is exactly correct. - The edge case of a grid with no uncovered cells returns
0before any BFS or binary search runs.
Complexity
- Time: O(R·C · log(max(R, C))). The BFS and prefix-sum build are each O(R·C). Each feasibility check scans uncovered cells in O(R·C) and queries in O(1). The binary search runs at most ~9 iterations on a 500×500 grid.
- Space: O(R·C) for the distance table and prefix-sum table.
Edge cases
| Scenario | Behavior |
|---|---|
All 1s | No uncovered cells → return 0 immediately |
All 0s | No BFS; high = max(rows-1, cols-1); a 1×1 grid gives high = 0, so answer is 0 |
| Single row or column | Chebyshev squares become intervals; logic is unchanged |
| Already optimal | Binary search lands on the current max distance; found_bad = False returns True |
Walkthrough of Example 1
Grid is [[0,0,0,1],[0,0,0,1]]. BFS distances by column: 3, 2, 1, 0. So high = 3.
- L = 1: bad cells are columns 0 and 1 in both rows. Their placement squares intersect to rows
[0,1], cols[0,1]. That rectangle contains zeros → feasible. Sethigh = 1. - L = 0: every zero is bad, and no single cell is within distance 0 of all of them → not feasible. Set
low = 1.
low == high == 1, so the answer is 1.
Full solution
from collections import deque
from typing import List
def min_coverage_gap(grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
uncovered = []
relays = []
dist = [[-1] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
relays.append((r, c))
dist[r][c] = 0
else:
uncovered.append((r, c))
if not uncovered:
return 0
if relays:
queue = deque(relays)
while queue:
r, c = queue.popleft()
for dr, dc in ((-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
high = max(dist[r][c] for r, c in uncovered)
else:
high = max(rows - 1, cols - 1)
prefix = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
row_sum = 0
for c in range(cols):
row_sum += 1 if grid[r][c] == 0 else 0
prefix[r + 1][c + 1] = prefix[r][c + 1] + row_sum
def has_uncovered(top: int, bottom: int, left: int, right: int) -> bool:
top = max(0, top)
bottom = min(rows - 1, bottom)
left = max(0, left)
right = min(cols - 1, right)
if top > bottom or left > right:
return False
count = (prefix[bottom + 1][right + 1]
- prefix[top][right + 1]
- prefix[bottom + 1][left]
+ prefix[top][left])
return count > 0
def feasible(limit: int) -> bool:
low_r, high_r = 0, rows - 1
low_c, high_c = 0, cols - 1
found_bad = False
for r, c in uncovered:
if relays and dist[r][c] <= limit:
continue
found_bad = True
low_r = max(low_r, r - limit)
high_r = min(high_r, r + limit)
low_c = max(low_c, c - limit)
high_c = min(high_c, c + limit)
if low_r > high_r or low_c > high_c:
return False
if not found_bad:
return True
return has_uncovered(low_r, high_r, low_c, high_c)
low = 0
while low < high:
mid = (low + high) // 2
if feasible(mid):
high = mid
else:
low = mid + 1
return low