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) with grid[r][c] == 1 represents an active household, while grid[r][c] == 0 represents an unoccupied block.
  • You may place a single distribution hub at any grid coordinate (R, C), whether that cell currently holds 0 or 1.
  • 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, where M = len(grid) and N = len(grid[0]) when M > 0.
  • Every entry grid[r][c] is either 0 or 1.
  • For Part 2, 0 <= len(customers) <= 10^5 and each character is 'Y' or 'N'.

Step-by-step walkthrough

  1. 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, grid is an M x N matrix of 0s and 1s where each 1 marks an active household cell (r, c). We place one hub on any cell (R, C) in the grid (including right on top of a 1) 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 = 4
    

    If grid contains zero 1s, nobody needs to travel anywhere, so the minimum total distance is 0.

  2. Part 1 brute force: try every grid cell as the hub

    The most direct solution collects all K household coordinates (dr, dc) where grid[dr][dc] == 1, then tries placing the hub on each of the M * N cells (r, c) and adds up |r - dr| + |c - dc| across all K households.

    Why is that too slow? When a grid is mostly 1s, K is roughly M * N, making the total work O((M * N)^2). On a 300 x 300 grid (90,000 cells), (90,000)^2 is 8.1 billion distance calculations — seconds or minutes in Python for a single test case.

  3. 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 R can be any row 0 .. M - 1 and C can be any column 0 .. N - 1 independently, choosing R has zero effect on the column sum, and choosing C has 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!

  4. 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 at x to minimize sum(|v_i - x|)?

    Imagine a tug-of-war as you take 1 step to the right from x to x + 1:

    • Every household at or behind x (v_i <= x) is now 1 unit farther (+1 each).
    • Every household strictly ahead of x (v_i > x) is now 1 unit closer (-1 each).
    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, change is negative, so walking right shrinks the total distance. The exact moment at least half the households are at or behind x, change turns 0 or 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!)
    
  5. Collect sorted row and column coordinates without sorting

    To read sorted_values[len(sorted_values) // 2], we need rows and cols in non-decreasing order. Instead of calling .sort() (O(K log K)), we let the loop order sort them for free in O(M * N) time:

    • Scanning row by row (for r in range(height): for c in range(width):) visits r = 0, then r = 1, ..., so rows is automatically sorted.
    • Scanning column by column (for c in range(width): for r in range(height):) visits c = 0, then c = 1, ..., so cols is 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)
    
  6. 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)
    
    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.
    2. Column-major scan: visits column 0 ((0, 0)), column 1 ((2, 1)), column 3 ((0, 3)) -> cols = [0, 1, 3].
      • median = cols[3 // 2] = 1.
      • Column distance sum = |0 - 1| + |1 - 1| + |3 - 1| = 3.
    3. Total minimum distance: 2 + 3 = 5, achieved by placing the hub on (0, 1) (notice (0, 1) is an unoccupied 0 cell — restricting the hub to 1 cells would have cost 6!).
  7. 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 during 0 .. t - 1 and closed during t .. n - 1. Counting idle open 'N' hours plus missed closed 'Y' hours from scratch for every t takes O(n^2) time.

    Instead, start at t = 0 (closed all day), where the cost is simply the total count of 'Y's in customers. When we push the closing time one hour later from hour to hour + 1, only customers[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
    
  8. 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 sorted rows = [0, 0, 2] with median 0 and row distance 0 + 0 + |2 - 0| = 2; scanning column-by-column gives sorted cols = [0, 1, 3] with median 1 and column distance |0 - 1| + 0 + |3 - 1| = 3, so the minimum total distance is 2 + 3 = 5 at (0, 1).
  • Part 2 on "YNYNY": starting at t = 0 gives cost 3 (three missed 'Y's); opening hours 0..4 one by one updates the cost to 2, 3, 2, 3, 2, and strict < keeps the earliest minimum t = 1.

Complexity

  • Part 1 Time: O(M * N), where M is the number of rows and N is the number of columns. We scan all M * N cells twice (once row-major, once column-major) so rows and cols come out already sorted without calling sort(), and then make one O(K) pass (K <= M * N) over each list to sum distances to the median.
  • Part 1 Space: O(K), where K is the number of 1 cells. We store one row index in rows and one column index in cols per 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), where n is len(customers). One pass counts 'Y's for t = 0, a second pass slides t from 1 to n in constant work per hour, and only a handful of integer variables are stored.

Edge cases

  • No active cells ([[0, 0], [0, 0]], [], or [[]]): rows and cols are empty, and 0 is returned without indexing sorted_values[0].
  • Single household (K = 1): placing the hub right on the household's own cell is allowed and yields total distance 0.
  • 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), so sorted_values[K // 2] works for both odd and even K.
  • Multiple households sharing a row or column: duplicates in rows and cols (such as rows = [0, 0, 2]) must be preserved because every household travels individually.
  • Part 2 extremes: "NNNN" never drops below its t = 0 cost (0), "YYYY" reaches cost 0 at t = 4 (n is a valid closing hour), and "" returns 0.

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 mean 3 gives 3 + 3 + 6 = 12 whereas the median 0 gives 0 + 0 + 9 = 9.
  • Collecting cols during the row-major loop without sorting: row-major order sorts rows but scrambles cols (giving cols = [0, 3, 1] on Example 1, whose middle element 3 gives the wrong answer 7 instead of 5).
  • Only checking household cells (1s) as candidate hubs: the optimal cell (median_row, median_col) is often an unoccupied 0 cell, 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 row 0.
  • Part 2 tie-breaking with <= instead of <: using penalty <= best_penalty overwrites best_time on ties and returns t = 5 instead of the earliest t = 1 on "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 elements sorted_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 in row_count[0..M-1], compute row_cost[0], and sweep row_cost[r + 1] = row_cost[r] + seen_so_far - remaining (and similarly col_cost[0..N-1]). This reduces extra memory to O(M + N) and gives the exact total distance row_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 a 1 cell, precompute the 1D cost arrays row_cost[0..M-1] and col_cost[0..N-1] in O(M * N) time using row and column household counts. Then scan every cell with grid[r][c] == 0 and take the minimum of row_cost[r] + col_cost[c] in O(M * N) total time (returning -1 or raising an error if no 0 cell 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 the K households, accumulate total distance and reachability counts per cell, and pick the cell reachable by all K households with the smallest sum in O(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]) in O(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 sum row_sum[r] * |r - median_row| plus col_sum[c] * |c - median_col| in O(M + N) additional time and space.

Follow-up questions

Similar questions

More Ge interview questions

All 2 Ge questions →