KatInterview

Reduce Worst-Case Coverage Gap with One New Relay Node

Trees & GraphsAuto-graded · 22 test cases
HardAuto-gradedTrees & Graphsbinary-searchbfsmatrix

Last 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 0 by 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 <= 500
  • 1 <= cols <= 500
  • Every cell value is 0 or 1
  • 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.