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) <= 5001 <= len(grid[0]) <= 500- Every
grid[r][c]is either0or1. - All rows of
gridhave the same length.
Step-by-step walkthrough
Understand Chebyshev distance and the goal
Each cell in
gridholds 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
Dof a hubCforms 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 2We may upgrade at most one
0cell into a1cell, and we want to minimize the grid's inconvenience—the worst-case distance from any remaining0cell to its closest1cell. Keep three boundary rules in mind:- The initial grid might have no
1at all; placing one hub makes all distances finite. - If no
0cells remain after our optional upgrade (for example[[0]]->[[1]]or[[1, 0]]->[[1, 1]]), the inconvenience is0. - Leaving the grid unchanged is allowed when existing hubs are already optimal.
- The initial grid might have no
Why trying every 0 cell directly is too slow
A direct brute-force tries every
0cell as the new center (plus the "add nothing" option) and scans the entireR x Cgrid to compute the worst distance for each candidate. Even if distances to existing centers are precomputed, testing up toR * Ccandidate placements takesO((R * C)^2)work—around6 * 10^10cell checks on a500 x 500grid.Instead of asking "which
0cell 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 distanceDof a center?Precompute distances to existing centers with multi-source BFS
Before testing any limit
D, we wantdist[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 existing1cell into a FIFO queue at distance0, then repeatedly pop a cell and visit its 8 king-move neighbors (drin-1, 0, 1anddcin-1, 0, 1). Because there are no walls, each BFS layer advances Chebyshev distance by1.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 distancemax(rows, cols) - 1inside the grid. When no1exists, every cell stays atrows + cols, so every cell will automatically exceed any candidatelimitwe 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 distKey insight: check a target limit D with a bounding box
Now fix a candidate limit
limit = D. Any cell withdist[r][c] <= Dis already covered by an existing center. Call the remaining cells—those withdist[r][c] > D—the far cells. Our single new center must cover every far cell within Chebyshev distanceD.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 * DWhy don't we need extra checks that
(r0, c0)stays inside the grid and lands on a0cell?- Inside the grid: Choose
r0 = max(0, max_r - D)andc0 = max(0, max_c - D). Sincemax_r <= rows - 1, we have0 <= r0 <= rows - 1; and sincemax_r - D <= min_r + Dand0 <= min_r + D, every far row in[min_r .. max_r]lies withinDofr0(and likewise forc0). - Must be a
0cell: When at least one far cell exists,(r0, c0)cannot already be an existing1—if it were, every far cell would already be within distanceDof(r0, c0)and would not have haddist > 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- Inside the grid: Choose
Binary search for the smallest valid limit
Notice that
can_cover_far_cells(dist, D)is monotonic: if distanceDworks, thenD + 1works too (fewer cells count as far, and2 * (D + 1)is even wider). So acrossD = 0, 1, 2, ..., the results look likeFalse, False, ..., False, True, True, ..., and we can binary search for the firstTrue:low = 0: smallest possible inconvenience (achievable when no0cells remain).high = max(rows, cols) - 1: guaranteed to work, because even a center at(0, 0)reaches every cell of anrows x colsgrid withinmax(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 lowTrace 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 returns2.Example 2:
2 x 7grid of all0s. Every cell getsdist = 2 + 7 = 9, so for everymidin[0, 6]the far-cell box spans the entire grid (row_span = 1,col_span = 6).mid = 2fails (col_span = 6 > 4), whilemid = 3succeeds (1 <= 6and6 <= 6), returning3.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))), whereRis the number of rows andCis the number of columns. Multi-source BFS visits each of theR * Ccells at most once and checks 8 neighbors (O(R * C)), and the binary search runs at mostceil(log2(max(R, C)))iterations (at most 9 for500 x 500), each performing oneO(R * C)grid scan. - Space:
O(R * C). Storing theR x Cdistance matrix and the BFS queue each use at mostR * Centries.
Edge cases
- No existing delivery centers (
all 0s): every cell keeps the initial sentineldist = R + C, so every cell is treated as far and the new center is placed near the middle of the grid, achievingceil((max(R, C) - 1) / 2). - No ordinary cells remain after conversion (
[[0]],[[1, 0]], or all1s): forD = 0, at most a single cell hasdist > 0(row_span = 0 <= 0andcol_span = 0 <= 0), cleanly returning0. - Adding a center cannot improve the answer (
[[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]): both ends are distance5apart on opposite sides (col_span = 10), so no radiusD < 5has10 <= 2 * D, and the answer stays5. - Diagonal coverage:
(0, 0)to(1, 1)has Chebyshev distance1(not2), so a single center at(1, 1)covers an entire3 x 3grid within1. - Single-row (
1 x C) or single-column (R x 1) grids:row_spanorcol_spanis0, andhigh = max(R, C) - 1still brackets the answer (0whenR = 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
-1when the grid has no1s: ifdiststays-1, the checkdist[r][c] > limitisFalseeverywhere forlimit >= 0, tricking the algorithm into returning0on 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 index8leaves index4at distance4, whereas placing it in the middle of the far region (index5or6) achieves distance3. - Off-by-one in the bounding-box width (
<= 2 * limit + 1instead of<= 2 * limit): a square of2 * D + 1cells has index span(r0 + D) - (r0 - D) = 2 * D, not2 * D + 1.
Alternative approaches
- Pure
O(R * C)bucket sweep without binary search: After theO(R * C)BFS, group cells into buckets by theirdistvalue (0 .. max(R, C)orunreached) and sweep from the largest distance bucket down to1, maintaining the runningmin_r, max_r, min_c, max_cof all cells strictly aboveD. That removes thelog(max(R, C))factor at the cost of extra bucket arrays; for500 x 500,log2(500) <= 9makes 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 (orNonewhen none is needed)? Once binary search finds the optimal limitD, run one final pass to find the bounding box[min_r .. max_r] x [min_c .. max_c]of cells withdist[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 withinD, and sit on a0cell. - Suppose only a restricted subset of
0cells are eligible to host the new hub. How would you adapt the check? For a candidate limitD, 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-leftr x csubgrid so any rectangle sum can be queried inO(1)time) once inO(R * C)time, and insidecan_cover_far_cellsverify that the valid center rectangle contains at least one eligible cell. Because enlargingDonly 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 switchnearest_center_distancesto a 4-neighbor BFS. Next apply the classic 45-degree coordinate rotationu = r + candv = 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 needu0 + v0even and0 <= r0 < R,0 <= c0 < C), scan allR * Ccandidate cells (or derive the valid column interval per row inO(R)) to check whether at least one grid cell satisfiesmax_u - D <= r + c <= min_u + Dandmax_v - D <= r - c <= min_v + D.
Follow-up questions
- How can you also return a valid `(r, c)` coordinate for the newly added hub (or `None` when none is needed)?
- Suppose only a restricted subset of `0` cells are eligible to host the new hub. How would you adapt the check?
- What changes if travel distance uses 4-directional Manhattan distance `|r1 - r2| + |c1 - c2|` instead of Chebyshev distance?
Similar questions
- Place One Hub to Minimize Maximum Grid Distance
- Evaluate Large Batches of Variable Ratio Queries
- SQL Daily Active Users and Distinct Palindromic Subsequences
- Single-Domain BFS Web Crawler
- In-Memory Inverted Sentence Index
- Design an O(1) LRU Cache
More Amazon interview questions
- Lowest Inversion Count When Merging Two Strings Hard
- Consolidate Overlapping Intervals Medium
- Amazon Final-Round Intern Behavioral Prompts Easy Pro
- Amazon Onsite Leadership Principles Behavioral Loop Medium Pro
- Leadership and Generative AI Behavioral Screen Easy Pro
- Amazon Software Engineering Intern Behavioral Screen Hard Pro
- Core Engineering Ownership and Leadership Prompts Medium Pro
- Data Science Behavioral Scenarios on Amazon Leadership Principles Medium Pro
- Target Sum Pair and Longest Unique Substring Medium Pro
- String Rearrangement, K-Way List Merge, and Random-Pointer Cloning Medium Pro