Grid Hub Placement for Minimum Manhattan Distance
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
This problem pairs a primary 2D grid optimization task (evaluated by the automated judge) with a 1D hourly scheduling problem from the same interview set.
Part 1 — Grid Hub Placement (minimize_total_distance)
You are given an M x N binary matrix grid filled with 0s and 1s:
def minimize_total_distance(grid: List[List[int]]) -> int:
- Each cell
(r, c)withgrid[r][c] == 1represents an active household, whilegrid[r][c] == 0represents an unoccupied block. - You may place a single distribution hub at any grid coordinate
(R, C), whether that cell currently holds0or1. - Travel cost between
(r, c)and(R, C)is measured by rectilinear (Manhattan) distance:|r - R| + |c - C|.
Return the smallest possible sum of Manhattan distances from all active households (1s) to the chosen hub. If grid is empty or contains zero 1s, return 0.
Part 2 — Companion Task: Earliest Optimal Closing Hour (best_closing_time)
Given an hourly visitor log string customers of length n containing only 'Y' (visitors arrived during hour i) and 'N' (nobody arrived during hour i), select an integer closing hour t in 0 .. n so the shop stays open during hours 0 .. t - 1 and closed during hours t .. n - 1. Each open hour with 'N' incurs +1 idle cost, and each closed hour with 'Y' incurs +1 missed-visitor cost. Return the earliest hour t that minimizes total cost (for example, "YNYNY" achieves its minimum cost of 2 earliest at t = 1).
Examples
Example 1
Input:
grid = [
[1, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 0, 0]
]
Output:
5
Walk-through: Active households sit at (0, 0), (0, 3), and (2, 1). Placing the hub on (0, 1) gives distances |0 - 0| + |0 - 1| = 1, |0 - 0| + |3 - 1| = 2, and |2 - 0| + |1 - 1| = 2, summing to 1 + 2 + 2 = 5. No other cell achieves a smaller total.
Example 2
Input:
grid = [
[0, 1],
[1, 0],
[0, 0]
]
Output:
2
Walk-through: With households at (0, 1) and (1, 0), placing the hub at (0, 1) (or (1, 1), (0, 0), or (1, 0)) yields 0 + 2 = 2 (or 1 + 1 = 2), which is minimal.
Constraints
0 <= M, N <= 300, whereM = len(grid)andN = len(grid[0])whenM > 0.- Every entry
grid[r][c]is either0or1. - For Part 2,
0 <= len(customers) <= 10^5and each character is'Y'or'N'.
Step-by-step walkthrough
Understand both tasks and their inputs
This problem bundles two independent optimization tasks. The automated judge evaluates Part 1 via
minimize_total_distance(grid); we will also solve Part 2 (best_closing_time(customers)) in its own step and include both in the complete solution.In Part 1,
gridis anM x Nmatrix of0s and1s where each1marks an active household cell(r, c). We place one hub on any cell(R, C)in the grid (including right on top of a1) to minimize the sum of Manhattan distances from every household to the hub.Manhattan distance
|r - R| + |c - C|measures travel along grid streets (vertical steps plus horizontal steps, with no diagonal shortcuts):Household at (2, 1) to Hub at (0, 3): vertical steps: |2 - 0| = 2 rows horizontal steps: |1 - 3| = 2 cols Manhattan distance = 2 + 2 = 4If
gridcontains zero1s, nobody needs to travel anywhere, so the minimum total distance is0.Part 1 brute force: try every grid cell as the hub
The most direct solution collects all
Khousehold coordinates(dr, dc)wheregrid[dr][dc] == 1, then tries placing the hub on each of theM * Ncells(r, c)and adds up|r - dr| + |c - dc|across allKhouseholds.Why is that too slow? When a grid is mostly
1s,Kis roughlyM * N, making the total workO((M * N)^2). On a300 x 300grid (90,000cells),(90,000)^2is8.1billion distance calculations — seconds or minutes in Python for a single test case.Key insight 1: split 2D Manhattan distance into two 1D problems
Write out the total distance when we place the hub at
(R, C)for households(r_1, c_1), (r_2, c_2), ..., (r_K, c_K):total(R, C) = (|r_1 - R| + |c_1 - C|) + (|r_2 - R| + |c_2 - C|) + ... + (|r_K - R| + |c_K - C|) = (|r_1 - R| + |r_2 - R| + ... + |r_K - R|) <-- depends ONLY on R! + (|c_1 - C| + |c_2 - C| + ... + |c_K - C|) <-- depends ONLY on C!Because
Rcan be any row0 .. M - 1andCcan be any column0 .. N - 1independently, choosingRhas zero effect on the column sum, and choosingChas zero effect on the row sum. We can minimize the 1D row sum and the 1D column sum separately and add the two answers together!Key insight 2: why the median minimizes 1D total distance
Now consider the 1D problem: given sorted household positions
v_0 <= v_1 <= ... <= v_{K-1}on a line, where should we stand atxto minimizesum(|v_i - x|)?Imagine a tug-of-war as you take 1 step to the right from
xtox + 1:- Every household at or behind
x(v_i <= x) is now1unit farther (+1each). - Every household strictly ahead of
x(v_i > x) is now1unit closer (-1each).
change = f(x + 1) - f(x) = (households at or left of x) - (households strictly right of x)As long as more than half the households are strictly ahead of
x,changeis negative, so walking right shrinks the total distance. The exact moment at least half the households are at or behindx,changeturns0or positive, so walking any farther right never helps.That balance point is the median — the middle item
sorted_values[K // 2]!Odd count: sorted_values = [0, 1, 3] (K = 3, median = sorted_values[1] = 1) At x = 0: |0-0| + |1-0| + |3-0| = 4 At x = 1: |0-1| + |1-1| + |3-1| = 3 <-- minimum At x = 2: |0-2| + |1-2| + |3-2| = 4 Even count: sorted_values = [0, 3] (K = 2, sorted_values[1] = 3) At x = 0, 1, 2, or 3: total is always 3 (every point between the two middle values ties!)- Every household at or behind
Collect sorted row and column coordinates without sorting
To read
sorted_values[len(sorted_values) // 2], we needrowsandcolsin non-decreasing order. Instead of calling.sort()(O(K log K)), we let the loop order sort them for free inO(M * N)time:- Scanning row by row (
for r in range(height): for c in range(width):) visitsr = 0, thenr = 1, ..., sorowsis automatically sorted. - Scanning column by column (
for c in range(width): for r in range(height):) visitsc = 0, thenc = 1, ..., socolsis automatically sorted.
def distance_to_median(sorted_values: List[int]) -> int: # sorted_values: non-decreasing 1D household coordinates, e.g. [0, 0, 2]. if len(sorted_values) == 0: return 0 # The median (middle element) minimizes sum(|v - x|); for even lengths, # both middle elements tie for the minimum, so len // 2 is always optimal. median = sorted_values[len(sorted_values) // 2] total_distance = 0 for value in sorted_values: total_distance += abs(value - median) return total_distance def minimize_total_distance(grid: List[List[int]]) -> int: if len(grid) == 0 or len(grid[0]) == 0: return 0 height = len(grid) width = len(grid[0]) # Phase 1: Row-major scan (top to bottom) collects household row indices already sorted. # Example on Example 1: rows = [0, 0, 2]. rows: List[int] = [] for r in range(height): for c in range(width): if grid[r][c] == 1: rows.append(r) # Phase 2: Column-major scan (left to right) collects household column indices already sorted, # avoiding an O(K log K) sort step. Example on Example 1: cols = [0, 1, 3]. cols: List[int] = [] for c in range(width): for r in range(height): if grid[r][c] == 1: cols.append(c) # Phase 3: Manhattan distance |r - R| + |c - C| splits into independent row and column totals. return distance_to_median(rows) + distance_to_median(cols)- Scanning row by row (
Walk through Example 1
Let's trace Example 1 (
grid = [[1, 0, 0, 1], [0, 0, 0, 0], [0, 1, 0, 0]]):col 0 col 1 col 2 col 3 row 0: 1 (0) 0 1 <-- households at (0, 0) and (0, 3), best hub at (0, 1) row 1: 0 0 0 0 row 2: 0 1 0 0 <-- household at (2, 1)- Row-major scan: finds
1s at(0, 0),(0, 3),(2, 1)->rows = [0, 0, 2].median = rows[3 // 2] = 0.- Row distance sum =
|0 - 0| + |0 - 0| + |2 - 0| = 2.
- Column-major scan: visits column
0((0, 0)), column1((2, 1)), column3((0, 3)) ->cols = [0, 1, 3].median = cols[3 // 2] = 1.- Column distance sum =
|0 - 1| + |1 - 1| + |3 - 1| = 3.
- Total minimum distance:
2 + 3 = 5, achieved by placing the hub on(0, 1)(notice(0, 1)is an unoccupied0cell — restricting the hub to1cells would have cost6!).
- Row-major scan: finds
Part 2: find the earliest optimal closing hour in one pass
In Part 2, closing at hour
t(0 <= t <= n) keeps the shop open during0 .. t - 1and closed duringt .. n - 1. Counting idle open'N'hours plus missed closed'Y'hours from scratch for everyttakesO(n^2)time.Instead, start at
t = 0(closed all day), where the cost is simply the total count of'Y's incustomers. When we push the closing time one hour later fromhourtohour + 1, onlycustomers[hour]changes state (from closed to open):- If
customers[hour] == "Y", that visitor hour is no longer missed ->penalty -= 1. - If
customers[hour] == "N", the shop now sits open with nobody arriving ->penalty += 1.
customers = "YNYNY" t = 0 (closed all day: | Y N Y N Y): missed 3 'Y's -> penalty = 3 (best = 3, best_time = 0) t = 1 (hour 0='Y' opens: Y | N Y N Y): 3 - 1 -> penalty = 2 (best = 2, best_time = 1) t = 2 (hour 1='N' opens: Y N | Y N Y): 2 + 1 -> penalty = 3 (not < 2, keep t = 1) t = 3 (hour 2='Y' opens: Y N Y | N Y): 3 - 1 -> penalty = 2 (tie! 2 < 2 is False, keep t = 1) t = 4 (hour 3='N' opens: Y N Y N | Y): 2 + 1 -> penalty = 3 (not < 2, keep t = 1) t = 5 (hour 4='Y' opens: Y N Y N Y |): 3 - 1 -> penalty = 2 (tie! keep earliest t = 1)Using strict
<(if penalty < best_penalty:) guarantees we keep the earliest closing hour whenever multiple hours tie.def best_closing_time(customers: str) -> int: # Part 2 Phase 1: Start at closing time t = 0 (closed all day), where every 'Y' hour is missed (+1 penalty). penalty = 0 for arrival in customers: if arrival == "Y": penalty += 1 best_penalty = penalty best_time = 0 # Part 2 Phase 2: Moving the closing time from `hour` to `hour + 1` flips `customers[hour]` from closed to open. for hour in range(len(customers)): if customers[hour] == "Y": # A previously missed customer hour is now served while open. penalty -= 1 else: # An hour with no customers ('N') now sits open for nobody. penalty += 1 # Strict `<` (not `<=`) ensures ties keep the earliest closing time t. if penalty < best_penalty: best_penalty = penalty best_time = hour + 1 return best_time- If
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def distance_to_median(sorted_values: List[int]) -> int: # sorted_values: non-decreasing 1D household coordinates, e.g. [0, 0, 2]. if len(sorted_values) == 0: return 0 # The median (middle element) minimizes sum(|v - x|); for even lengths, # both middle elements tie for the minimum, so len // 2 is always optimal. median = sorted_values[len(sorted_values) // 2] total_distance = 0 for value in sorted_values: total_distance += abs(value - median) return total_distance def minimize_total_distance(grid: List[List[int]]) -> int: if len(grid) == 0 or len(grid[0]) == 0: return 0 height = len(grid) width = len(grid[0]) # Phase 1: Row-major scan (top to bottom) collects household row indices already sorted. # Example on Example 1: rows = [0, 0, 2]. rows: List[int] = [] for r in range(height): for c in range(width): if grid[r][c] == 1: rows.append(r) # Phase 2: Column-major scan (left to right) collects household column indices already sorted, # avoiding an O(K log K) sort step. Example on Example 1: cols = [0, 1, 3]. cols: List[int] = [] for c in range(width): for r in range(height): if grid[r][c] == 1: cols.append(c) # Phase 3: Manhattan distance |r - R| + |c - C| splits into independent row and column totals. return distance_to_median(rows) + distance_to_median(cols) def best_closing_time(customers: str) -> int: # Part 2 Phase 1: Start at closing time t = 0 (closed all day), where every 'Y' hour is missed (+1 penalty). penalty = 0 for arrival in customers: if arrival == "Y": penalty += 1 best_penalty = penalty best_time = 0 # Part 2 Phase 2: Moving the closing time from `hour` to `hour + 1` flips `customers[hour]` from closed to open. for hour in range(len(customers)): if customers[hour] == "Y": # A previously missed customer hour is now served while open. penalty -= 1 else: # An hour with no customers ('N') now sits open for nobody. penalty += 1 # Strict `<` (not `<=`) ensures ties keep the earliest closing time t. if penalty < best_penalty: best_penalty = penalty best_time = hour + 1 return best_time✅ Submit now — all tests should pass.
Intuition & how it works
Imagine choosing a hub corner in a city laid out on a rectangular street grid where people walk along blocks rather than cutting diagonally. That block-by-block travel is Manhattan distance — the vertical distance |r1 - r2| plus the horizontal distance |c1 - c2|. Because a hub's row only affects everyone's north-south walk and its column only affects everyone's east-west walk, the 2D grid problem splits cleanly into two independent 1D number-line problems. On a 1D line, if you play tug-of-war between households to your left and households to your right, total walking distance is always minimized by standing at the median — the middle value when all household positions are listed in sorted order. (For Part 2's closing hour, sliding the "Closed" boundary one hour later flips only that single hour from closed to open, letting us update the cost by -1 or +1 in one pass.)
Why do the naive approaches fall short? Testing every cell (r, c) on an M x N grid and summing distances to all K households takes O(M * N * K) time, which reaches (M * N)^2 (8.1 billion additions on a full 300 x 300 grid). Likewise, recounting idle 'N' hours and missed 'Y' hours from scratch for every closing hour t in 0..n repeats the same work n + 1 times in O(n^2) time.
Tracing both algorithms on our examples makes the speedup concrete:
- Part 1 on
[[1, 0, 0, 1], [0, 0, 0, 0], [0, 1, 0, 0]](households at(0, 0),(0, 3),(2, 1)): scanning row-by-row gives sortedrows = [0, 0, 2]with median0and row distance0 + 0 + |2 - 0| = 2; scanning column-by-column gives sortedcols = [0, 1, 3]with median1and column distance|0 - 1| + 0 + |3 - 1| = 3, so the minimum total distance is2 + 3 = 5at(0, 1). - Part 2 on
"YNYNY": starting att = 0gives cost3(three missed'Y's); opening hours0..4one by one updates the cost to2, 3, 2, 3, 2, and strict<keeps the earliest minimumt = 1.
Complexity
- Part 1 Time:
O(M * N), whereMis the number of rows andNis the number of columns. We scan allM * Ncells twice (once row-major, once column-major) sorowsandcolscome out already sorted without callingsort(), and then make oneO(K)pass (K <= M * N) over each list to sum distances to the median. - Part 1 Space:
O(K), whereKis the number of1cells. We store one row index inrowsand one column index incolsper household (O(M + N)is also possible if you store per-row and per-column counts instead of raw lists). - Part 2 Time:
O(n)and Space:O(1), wherenislen(customers). One pass counts'Y's fort = 0, a second pass slidestfrom1tonin constant work per hour, and only a handful of integer variables are stored.
Edge cases
- No active cells (
[[0, 0], [0, 0]],[], or[[]]):rowsandcolsare empty, and0is returned without indexingsorted_values[0]. - Single household (
K = 1): placing the hub right on the household's own cell is allowed and yields total distance0. - Even number of households (
[[0, 1], [1, 0], [0, 0]]): every integer coordinate between the two middle values achieves the exact same minimum total (2), sosorted_values[K // 2]works for both odd and evenK. - Multiple households sharing a row or column: duplicates in
rowsandcols(such asrows = [0, 0, 2]) must be preserved because every household travels individually. - Part 2 extremes:
"NNNN"never drops below itst = 0cost (0),"YYYY"reaches cost0att = 4(nis a valid closing hour), and""returns0.
Common mistakes
- Using the arithmetic mean (average) instead of the median: the mean minimizes squared Euclidean distances, not absolute Manhattan distances; on
rows = [0, 0, 9], the mean3gives3 + 3 + 6 = 12whereas the median0gives0 + 0 + 9 = 9. - Collecting
colsduring the row-major loop without sorting: row-major order sortsrowsbut scramblescols(givingcols = [0, 3, 1]on Example 1, whose middle element3gives the wrong answer7instead of5). - Only checking household cells (
1s) as candidate hubs: the optimal cell(median_row, median_col)is often an unoccupied0cell, such as(0, 1)in Example 1. - Deduplicating coordinates with a
set: collapsing[0, 0, 2]to{0, 2}ignores the weight of having two households on row0. - Part 2 tie-breaking with
<=instead of<: usingpenalty <= best_penaltyoverwritesbest_timeon ties and returnst = 5instead of the earliestt = 1on"YNYNY".
Alternative approaches
- Two-pointer outer pairing (
O(M * N)time,O(K)space): on a sorted array,sum(|v - median|)equals pairing the outermost elementssorted_values[right] - sorted_values[left]inward (left += 1,right -= 1), because the median sits between every outer pair. - Prefix-sweep row and column cost arrays (
O(M * N)time,O(M + N)space): count households per row inrow_count[0..M-1], computerow_cost[0], and sweeprow_cost[r + 1] = row_cost[r] + seen_so_far - remaining(and similarlycol_cost[0..N-1]). This reduces extra memory toO(M + N)and gives the exact total distancerow_cost[r] + col_cost[c]for every cell(r, c).
Follow-up questions
- How would you adapt the algorithm if the hub can only be placed on an unoccupied cell where grid[r][c] == 0? Because
(median_row, median_col)might land on a1cell, precompute the 1D cost arraysrow_cost[0..M-1]andcol_cost[0..N-1]inO(M * N)time using row and column household counts. Then scan every cell withgrid[r][c] == 0and take the minimum ofrow_cost[r] + col_cost[c]inO(M * N)total time (returning-1or raising an error if no0cell exists). - What if certain grid cells contain impassable barriers that force travel paths to detour around them? Barriers break the Manhattan formula
|r1 - r2| + |c1 - c2|because shortest paths can bend, so rows and columns can no longer be solved separately. Instead, run a breadth-first search (BFS) — a layer-by-layer grid search that finds shortest unweighted paths from a starting cell to all reachable cells — starting from each of theKhouseholds, accumulate total distance and reachability counts per cell, and pick the cell reachable by allKhouseholds with the smallest sum inO(K * M * N)time. - How would you generalize the solution if grid[r][c] holds an arbitrary non-negative integer weight representing household count? Sum the household weights in each row (
row_sum[r]) and in each column (col_sum[c]) inO(M * N)time, rather than expanding millions of duplicate coordinates into a list. Then find the weighted median — the first row (and first column) where the running sum of weights reaches at least half of all total weight — and sumrow_sum[r] * |r - median_row|pluscol_sum[c] * |c - median_col|inO(M + N)additional time and space.
Follow-up questions
- How would you adapt the algorithm if the hub can only be placed on an unoccupied cell where grid[r][c] == 0?
- What if certain grid cells contain impassable barriers that force travel paths to detour around them?
- How would you generalize the solution if grid[r][c] holds an arbitrary non-negative integer weight representing household count?
Similar questions
- Rightward Visibility Counts in a Queue
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One