Minimizing Worst-Case Grid Distance with One Extra Hub

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given a rectangular 2D integer matrix grid of size R x C, where each cell holds either 1 (an active supply hub) or 0 (a regular cell). Travel distance between any two coordinates (r1, c1) and (r2, c2) is measured by Chebyshev distance:

dist((r1, c1), (r2, c2)) = max(abs(r1 - r2), abs(c1 - c2))

Distances depend purely on row and column coordinates—diagonal steps cost 1 just like orthogonal steps, and no cells block movement.

The inconvenience of a grid is defined as the maximum Chebyshev distance from any 0 cell to its closest 1 cell. Before measuring inconvenience, you are allowed to upgrade at most one 0 cell into a 1 cell (you may also choose to make no change). Existing 1 cells cannot be relocated or removed.

Implement:

def get_min_inconvenience(grid: List[List[int]]) -> int:

Return the smallest inconvenience achievable after converting zero or one 0 cell into 1 (return only the minimum distance value, not the chosen cell's coordinates).

Keep two boundary conventions in mind: - grid may initially contain no 1 cells at all; upgrading one 0 cell to 1 then provides the hub against which remaining 0 cells are measured. - If zero 0 cells remain after your optional upgrade, the grid's inconvenience is 0.

Examples

Example 1

Input:
grid = [
  [1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0]
]
Output: 2

Upgrading (1, 4) to 1 brings columns 2..5 across all three rows within Chebyshev distance 2 of (1, 4), while the existing hub at (0, 0) already covers (2, 0), (2, 1), and (2, 2) within distance 2. Achieving 1 is impossible because the cells farther than 1 from (0, 0) include both (2, 0) in column 0 and (0, 5) in column 5, which are 5 columns apart.

Example 2

Input:
grid = [
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0]
]
Output: 3

No hub is present at the start. Upgrading (0, 3) (or (1, 3)) places every cell in both rows and all 7 columns within max(1, 3) = 3 king steps. Because a single hub at radius 2 covers at most 2 * 2 + 1 = 5 columns, 3 is optimal.

Constraints

  • 1 <= len(grid) <= 500
  • 1 <= len(grid[0]) <= 500
  • Every grid[r][c] is either 0 or 1.
  • All rows of grid have the same length.

Step-by-step walkthrough

  1. Understand Chebyshev distance and the goal

    Each cell in grid holds either an active supply hub (1) or a regular cell (0). Distance between two coordinates (r1, c1) and (r2, c2) is measured using Chebyshev distance:

    distance = max(|r1 - r2|, |c1 - c2|)
    

    On a chessboard, Chebyshev distance is the minimum number of king moves (one step horizontally, vertically, or diagonally) between two squares. That means the set of cells within Chebyshev distance D of a hub C forms a solid (2 * D + 1) by (2 * D + 1) square:

    2 2 2 2 2
    2 1 1 1 2      D = 1 covers a 3 x 3 square (row/col span 2)
    2 1 C 1 2      D = 2 covers a 5 x 5 square (row/col span 4)
    2 1 1 1 2
    2 2 2 2 2
    

    We may upgrade at most one 0 cell into a 1 cell, and we want to minimize the grid's inconvenience—the worst-case distance from any remaining 0 cell to its closest 1 cell. Keep three boundary rules in mind:

    • The initial grid might have no 1 at all; placing one hub makes all distances finite.
    • If no 0 cells remain after our optional upgrade (for example [[0]] -> [[1]] or [[1, 0]] -> [[1, 1]]), the inconvenience is 0.
    • Leaving the grid unchanged is allowed when existing hubs are already optimal.
  2. Why trying every 0 cell directly is too slow

    A direct brute-force tries every 0 cell as the new center (plus the "add nothing" option) and scans the entire R x C grid to compute the worst distance for each candidate. Even if distances to existing centers are precomputed, testing up to R * C candidate placements takes O((R * C)^2) work—around 6 * 10^10 cell checks on a 500 x 500 grid.

    Instead of asking "which 0 cell gives the smallest worst distance?", flip the question around:

    Given a target distance limit D, can at most one new center bring every cell within distance D of a center?

  3. Precompute distances to existing centers with multi-source BFS

    Before testing any limit D, we want dist[r][c], the Chebyshev distance from every cell (r, c) to its nearest existing center.

    A multi-source breadth-first search (BFS) computes all of them in a single O(R * C) pass: push every existing 1 cell into a FIFO queue at distance 0, then repeatedly pop a cell and visit its 8 king-move neighbors (dr in -1, 0, 1 and dc in -1, 0, 1). Because there are no walls, each BFS layer advances Chebyshev distance by 1.

    What if the grid starts with zero centers? We initialize every cell to unreached = rows + cols, which is strictly larger than the maximum possible Chebyshev distance max(rows, cols) - 1 inside the grid. When no 1 exists, every cell stays at rows + cols, so every cell will automatically exceed any candidate limit we test!

    def nearest_center_distances(grid: List[List[int]]) -> List[List[int]]:
        """Compute Chebyshev distance from every cell to its nearest existing center."""
        rows = len(grid)
        cols = len(grid[0])
        # `unreached` is strictly larger than max possible grid distance max(rows, cols) - 1.
        # If the grid has no centers at all, every cell stays at `unreached`.
        unreached = rows + cols
        dist = [[unreached] * cols for _ in range(rows)]
        queue = deque()  # FIFO queue of (row, col) cells in increasing distance order
    
        # Phase 1: seed multi-source BFS with all existing delivery centers at distance 0.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    dist[r][c] = 0
                    queue.append((r, c))
    
        # Phase 2: expand 8-directionally (chess king moves); each layer adds +1 Chebyshev distance.
        while queue:
            r, c = queue.popleft()
            next_dist = dist[r][c] + 1
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    nr = r + dr
                    nc = c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == unreached:
                        dist[nr][nc] = next_dist
                        queue.append((nr, nc))
    
        return dist
    
  4. Key insight: check a target limit D with a bounding box

    Now fix a candidate limit limit = D. Any cell with dist[r][c] <= D is already covered by an existing center. Call the remaining cells—those with dist[r][c] > D—the far cells. Our single new center must cover every far cell within Chebyshev distance D.

    Track the bounding box (smallest enclosing axis-aligned rectangle) of all far cells: their minimum and maximum row (min_r, max_r) and minimum and maximum column (min_c, max_c):

          min_c       max_c
    min_r  +--- F ------+
           |         F  |    Can one (2*D + 1) x (2*D + 1) square
           |  F         |    cover this entire box?
    max_r  +------ F ---+
    

    Because one center at (r0, c0) covers [r0 - D .. r0 + D] x [c0 - D .. c0 + D], one center can cover all far cells if and only if:

    max_r - min_r <= 2 * D    and    max_c - min_c <= 2 * D
    

    Why don't we need extra checks that (r0, c0) stays inside the grid and lands on a 0 cell?

    • Inside the grid: Choose r0 = max(0, max_r - D) and c0 = max(0, max_c - D). Since max_r <= rows - 1, we have 0 <= r0 <= rows - 1; and since max_r - D <= min_r + D and 0 <= min_r + D, every far row in [min_r .. max_r] lies within D of r0 (and likewise for c0).
    • Must be a 0 cell: When at least one far cell exists, (r0, c0) cannot already be an existing 1—if it were, every far cell would already be within distance D of (r0, c0) and would not have had dist > D!
    def can_cover_far_cells(dist: List[List[int]], limit: int) -> bool:
        """Return True if at most one new center brings every cell within `limit`."""
        rows = len(dist)
        cols = len(dist[0])
    
        # Track the bounding box [min_r .. max_r] x [min_c .. max_c] of cells with dist > limit.
        min_r = rows
        max_r = -1
        min_c = cols
        max_c = -1
        for r in range(rows):
            for c in range(cols):
                if dist[r][c] > limit:
                    if r < min_r:
                        min_r = r
                    if r > max_r:
                        max_r = r
                    if c < min_c:
                        min_c = c
                    if c > max_c:
                        max_c = c
    
        # If max_r stayed -1, every cell is already within `limit` without adding a center.
        if max_r == -1:
            return True
    
        # One center at (r0, c0) covers [r0 - limit .. r0 + limit] x [c0 - limit .. c0 + limit],
        # which spans at most 2 * limit between extreme row indices and extreme column indices.
        row_span = max_r - min_r
        col_span = max_c - min_c
        return row_span <= 2 * limit and col_span <= 2 * limit
    
  5. Binary search for the smallest valid limit

    Notice that can_cover_far_cells(dist, D) is monotonic: if distance D works, then D + 1 works too (fewer cells count as far, and 2 * (D + 1) is even wider). So across D = 0, 1, 2, ..., the results look like False, False, ..., False, True, True, ..., and we can binary search for the first True:

    • low = 0: smallest possible inconvenience (achievable when no 0 cells remain).
    • high = max(rows, cols) - 1: guaranteed to work, because even a center at (0, 0) reaches every cell of an rows x cols grid within max(rows, cols) - 1.
    def get_min_inconvenience(grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
        dist = nearest_center_distances(grid)
    
        # Binary search the smallest valid inconvenience D in [0 .. max(rows, cols) - 1].
        # Upper bound `high` always works because even one corner cell reaches the whole grid.
        low = 0
        high = max(rows, cols) - 1
        while low < high:
            mid = (low + high) // 2
            if can_cover_far_cells(dist, mid):
                high = mid
            else:
                low = mid + 1
    
        return low
    
  6. Trace Example 1 and Example 2

    Example 1: grid = [[1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] (3 x 6).

    Precomputed dist:                Test mid = 2 (far cells dist > 2):
    [ 0, 1, 2, 3, 4, 5 ]             [ ., ., ., F, F, F ]   min_r=0, max_r=2 -> row_span = 2 <= 4
    [ 1, 1, 2, 3, 4, 5 ]             [ ., ., ., F, F, F ]   min_c=3, max_c=5 -> col_span = 2 <= 4  -> True!
    [ 2, 2, 2, 3, 4, 5 ]             [ ., ., ., F, F, F ]
    
                                     Test mid = 1 (far cells dist > 1):
                                     [ ., ., F, F, F, F ]   min_c=0 (at row 2), max_c=5
                                     [ ., ., F, F, F, F ]   -> col_span = 5 > 2                   -> False!
                                     [ F, F, F, F, F, F ]
    

    Binary search narrows [0, 5] -> [0, 2] -> [2, 2] and returns 2.

    Example 2: 2 x 7 grid of all 0s. Every cell gets dist = 2 + 7 = 9, so for every mid in [0, 6] the far-cell box spans the entire grid (row_span = 1, col_span = 6). mid = 2 fails (col_span = 6 > 4), while mid = 3 succeeds (1 <= 6 and 6 <= 6), returning 3.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    def nearest_center_distances(grid: List[List[int]]) -> List[List[int]]:
        """Compute Chebyshev distance from every cell to its nearest existing center."""
        rows = len(grid)
        cols = len(grid[0])
        # `unreached` is strictly larger than max possible grid distance max(rows, cols) - 1.
        # If the grid has no centers at all, every cell stays at `unreached`.
        unreached = rows + cols
        dist = [[unreached] * cols for _ in range(rows)]
        queue = deque()  # FIFO queue of (row, col) cells in increasing distance order
    
        # Phase 1: seed multi-source BFS with all existing delivery centers at distance 0.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    dist[r][c] = 0
                    queue.append((r, c))
    
        # Phase 2: expand 8-directionally (chess king moves); each layer adds +1 Chebyshev distance.
        while queue:
            r, c = queue.popleft()
            next_dist = dist[r][c] + 1
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    nr = r + dr
                    nc = c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == unreached:
                        dist[nr][nc] = next_dist
                        queue.append((nr, nc))
    
        return dist
    
    
    def can_cover_far_cells(dist: List[List[int]], limit: int) -> bool:
        """Return True if at most one new center brings every cell within `limit`."""
        rows = len(dist)
        cols = len(dist[0])
    
        # Track the bounding box [min_r .. max_r] x [min_c .. max_c] of cells with dist > limit.
        min_r = rows
        max_r = -1
        min_c = cols
        max_c = -1
        for r in range(rows):
            for c in range(cols):
                if dist[r][c] > limit:
                    if r < min_r:
                        min_r = r
                    if r > max_r:
                        max_r = r
                    if c < min_c:
                        min_c = c
                    if c > max_c:
                        max_c = c
    
        # If max_r stayed -1, every cell is already within `limit` without adding a center.
        if max_r == -1:
            return True
    
        # One center at (r0, c0) covers [r0 - limit .. r0 + limit] x [c0 - limit .. c0 + limit],
        # which spans at most 2 * limit between extreme row indices and extreme column indices.
        row_span = max_r - min_r
        col_span = max_c - min_c
        return row_span <= 2 * limit and col_span <= 2 * limit
    
    
    def get_min_inconvenience(grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
        dist = nearest_center_distances(grid)
    
        # Binary search the smallest valid inconvenience D in [0 .. max(rows, cols) - 1].
        # Upper bound `high` always works because even one corner cell reaches the whole grid.
        low = 0
        high = max(rows, cols) - 1
        while low < high:
            mid = (low + high) // 2
            if can_cover_far_cells(dist, mid):
                high = mid
            else:
                low = mid + 1
    
        return low
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of each supply hub as a radio tower whose signal reaches D blocks in every direction—including diagonals—forming a (2 * D + 1) by (2 * D + 1) square on the map. Instead of testing every empty cell one by one to find the best new tower spot, pick a candidate radius D, highlight all the "dead-zone" cells that existing towers fail to reach within D, and check whether a single (2 * D + 1) square is wide and tall enough to cover that entire dead-zone rectangle at once.

Trying every 0 cell directly and scanning the R x C grid to recompute worst-case distances takes O((R * C)^2) work—over 6 * 10^10 cell visits on a 500 x 500 grid. Instead, we run one multi-source BFS (a breadth-first search started from all existing hubs simultaneously at distance 0) to find every cell's distance to its nearest existing hub under Chebyshev distance (max(|r1 - r2|, |c1 - c2|), the number of chessboard king moves). Then we use binary search on the answer (repeatedly halving the range of candidate radii D) and check each D in one scan by computing the bounding box (smallest enclosing rectangle [min_r .. max_r] x [min_c .. max_c]) of cells with dist > D and testing max_r - min_r <= 2 * D and max_c - min_c <= 2 * D.

Walk through grid = [[1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]: 1. Multi-source BFS from (0, 0) produces rows [0, 1, 2, 3, 4, 5], [1, 1, 2, 3, 4, 5], and [2, 2, 2, 3, 4, 5]. 2. Binary search starts on [0, 5] and tests mid = 2: the cells with dist > 2 sit at rows 0..2 and columns 3..5 (row_span = 2 <= 4, col_span = 2 <= 4), so D = 2 works (high = 2). 3. Next it tests mid = 1: the cells with dist > 1 include (2, 0) and (0, 5), spanning columns 0..5 (col_span = 5 > 2), so D = 1 fails (low = 2). 4. low == high == 2, returning the optimal inconvenience 2.

Complexity

  • Time: O(R * C * log(max(R, C))), where R is the number of rows and C is the number of columns. Multi-source BFS visits each of the R * C cells at most once and checks 8 neighbors (O(R * C)), and the binary search runs at most ceil(log2(max(R, C))) iterations (at most 9 for 500 x 500), each performing one O(R * C) grid scan.
  • Space: O(R * C). Storing the R x C distance matrix and the BFS queue each use at most R * C entries.

Edge cases

  • No existing delivery centers (all 0s): every cell keeps the initial sentinel dist = R + C, so every cell is treated as far and the new center is placed near the middle of the grid, achieving ceil((max(R, C) - 1) / 2).
  • No ordinary cells remain after conversion ([[0]], [[1, 0]], or all 1s): for D = 0, at most a single cell has dist > 0 (row_span = 0 <= 0 and col_span = 0 <= 0), cleanly returning 0.
  • Adding a center cannot improve the answer ([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]): both ends are distance 5 apart on opposite sides (col_span = 10), so no radius D < 5 has 10 <= 2 * D, and the answer stays 5.
  • Diagonal coverage: (0, 0) to (1, 1) has Chebyshev distance 1 (not 2), so a single center at (1, 1) covers an entire 3 x 3 grid within 1.
  • Single-row (1 x C) or single-column (R x 1) grids: row_span or col_span is 0, and high = max(R, C) - 1 still brackets the answer (0 when R = C = 1).

Common mistakes

  • Using 4-neighbor BFS instead of 8-neighbor BFS: 4-neighbor steps measure Manhattan distance (|dr| + |dc|, grid-street steps without diagonals) rather than Chebyshev distance, overestimating diagonal distances by up to 2x.
  • Leaving unvisited cells at -1 when the grid has no 1s: if dist stays -1, the check dist[r][c] > limit is False everywhere for limit >= 0, tricking the algorithm into returning 0 on an all-zero grid!
  • Greedily placing the new center on the single farthest cell: in [[1, 0, 0, 0, 0, 0, 0, 0, 0]], placing the new center at index 8 leaves index 4 at distance 4, whereas placing it in the middle of the far region (index 5 or 6) achieves distance 3.
  • Off-by-one in the bounding-box width (<= 2 * limit + 1 instead of <= 2 * limit): a square of 2 * D + 1 cells has index span (r0 + D) - (r0 - D) = 2 * D, not 2 * D + 1.

Alternative approaches

  • Pure O(R * C) bucket sweep without binary search: After the O(R * C) BFS, group cells into buckets by their dist value (0 .. max(R, C) or unreached) and sweep from the largest distance bucket down to 1, maintaining the running min_r, max_r, min_c, max_c of all cells strictly above D. That removes the log(max(R, C)) factor at the cost of extra bucket arrays; for 500 x 500, log2(500) <= 9 makes binary search already well under a tenth of a second.

Follow-up questions

  • How can you also return a valid (r, c) coordinate for the newly added hub (or None when none is needed)? Once binary search finds the optimal limit D, run one final pass to find the bounding box [min_r .. max_r] x [min_c .. max_c] of cells with dist[r][c] > D. If no such cell exists, no extra hub is needed (None); otherwise, (max(0, max_r - D), max(0, max_c - D)) is guaranteed to lie inside the grid, cover every far cell within D, and sit on a 0 cell.
  • Suppose only a restricted subset of 0 cells are eligible to host the new hub. How would you adapt the check? For a candidate limit D, the valid hub coordinates that cover [min_r .. max_r] x [min_c .. max_c] still form a clipped rectangle [max(0, max_r - D) .. min(R - 1, min_r + D)] x [max(0, max_c - D) .. min(C - 1, min_c + D)]. Precompute a 2D prefix sum (a table where entry (r, c) stores the count of eligible cells in the top-left r x c subgrid so any rectangle sum can be queried in O(1) time) once in O(R * C) time, and inside can_cover_far_cells verify that the valid center rectangle contains at least one eligible cell. Because enlarging D only shrinks the far-cell set and widens the valid center rectangle, monotonicity—and binary search—still holds.
  • What changes if travel distance uses 4-directional Manhattan distance |r1 - r2| + |c1 - c2| instead of Chebyshev distance? First switch nearest_center_distances to a 4-neighbor BFS. Next apply the classic 45-degree coordinate rotation u = r + c and v = r - c, which converts Manhattan distance into Chebyshev distance: |r1 - r2| + |c1 - c2| == max(|u1 - u2|, |v1 - v2|). Find [min_u .. max_u] and [min_v .. max_v] over all far cells; because not every (u0, v0) pair corresponds to an in-bounds integer grid cell (r0, c0) (we need u0 + v0 even and 0 <= r0 < R, 0 <= c0 < C), scan all R * C candidate cells (or derive the valid column interval per row in O(R)) to check whether at least one grid cell satisfies max_u - D <= r + c <= min_u + D and max_v - D <= r - c <= min_v + D.

Follow-up questions

Similar questions

More Amazon interview questions

All 653 Amazon questions →