Optimal Meetup Coordinates for Weighted Grid Travel
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
A list cities describes n settlements on a 2D coordinate grid. Entry i is a three-integer list [x_i, y_i, w_i], giving the horizontal coordinate x_i, vertical coordinate y_i, and resident count w_i of settlement i.
Choose an integer grid location (X, Y) that minimizes the aggregate resident travel effort measured along grid axes:
total_cost(X, Y) = sum over i of w_i * (|x_i - X| + |y_i - Y|)
Return a three-element list [cost, X, Y] containing the minimum possible total_cost followed by the chosen coordinates X and Y. Whenever more than one point (X, Y) achieves the exact same minimum total_cost, break ties by picking the smallest X, and if still tied, the smallest Y.
def min_weighted_manhattan(cities: List[List[int]]) -> List[int]:
Examples
Example 1
Input: cities = [[1, 3, 2], [5, 3, 2]]
Output: [8, 1, 3]
Explanation: Both settlements have weight 2 and lie on y = 3, so Y = 3 adds zero vertical travel. Every integer X from 1 through 5 produces horizontal cost 2 * |1 - X| + 2 * |5 - X| = 8. Tie-breaking picks the smallest X, giving (1, 3) with cost 8.
Example 2
Input: cities = [[2, 4, 8], [9, 7, 1]]
Output: [10, 2, 4]
Explanation: Eight of the nine residents already live at (2, 4), so placing the hub at (2, 4) requires only the single resident at (9, 7) to travel |9 - 2| + |7 - 4| = 7 + 3 = 10 grid units.
Example 3
Input: cities = [[2, 6, 4], [5, 1, 3], [9, 3, 5]]
Output: [50, 5, 3]
Explanation: Across 12 total residents, X = 5 balances horizontal travel (4 * 3 + 3 * 0 + 5 * 4 = 32) and Y = 3 balances vertical travel (4 * 3 + 3 * 2 + 5 * 0 = 18). Even though (5, 3) is not itself one of the input settlements, it achieves the unique minimum cost 32 + 18 = 50.
Constraints
1 <= len(cities) <= 10^50 <= x_i, y_i <= 10^61 <= w_i <= 1000
Step-by-step walkthrough
Understand the travel formula and tie-breaking rule
Each settlement is
[x, y, w]: its 2D grid position(x, y)and resident countw >= 1. When everyone travels along horizontal and vertical grid lines to a hub(X, Y), the total weighted travel effort is:total_cost(X, Y) = sum over all settlements of w * (|x - X| + |y - Y|)We must return
[cost, X, Y]minimizingtotal_cost(X, Y). Whenever multiple points tie for the lowest cost, we break ties in lexicographical order: pick the smallestX, and among those still tied, pick the smallestY.- Input:
1 <= len(cities) <= 10^5,0 <= x, y <= 10^6,1 <= w <= 1,000. - Output:
[cost, X, Y]as three integers.
- Input:
Why scanning the 2D bounding box is too slow
An optimal hub never lies outside the rectangle spanning the minimum and maximum settlement coordinates (stepping outside moves you farther from every settlement simultaneously). A brute-force search could test every integer grid point
(X, Y)inside that rectangle and evaluatetotal_cost(X, Y)inO(n)time per point.With coordinates up to
10^6, that bounding box holds up to10^6 * 10^6 = 10^12grid points, and summing over10^5settlements per point would require10^17operations. We need a mathematical decomposition.Split the 2D grid into two independent 1D lines
Expand each settlement's term
w * (|x - X| + |y - Y|)intow * |x - X| + w * |y - Y|. Collecting allxterms together and allyterms together splitstotal_cost(X, Y)into two completely independent sums:total_cost(X, Y) = cost_x(X) + cost_y(Y) where cost_x(X) = sum of w * |x - X| (depends ONLY on X!) and cost_y(Y) = sum of w * |y - Y| (depends ONLY on Y!)Changing
Xnever alterscost_y(Y), and changingYnever alterscost_x(X). Consequently:min total_cost(X, Y) = (min over X of cost_x(X)) + (min over Y of cost_y(Y)).- Tie-breaking also decouples cleanly: the smallest
Xamong optimal(X, Y)pairs is simply the smallestXminimizingcost_x(X), and the smallestYis the smallestYminimizingcost_y(Y).
One 2D grid problem reduces to two identical 1D number-line problems!
Find the balance point on a 1D line: the lowest weighted median
Suppose settlements sit along a single line with total population
W. PlaceXon the far left and slideXrightward by+1unit at a time:population <= X population > X (left_weight = L) (right_weight = W - L) o-------o-------[ X ]---> +1 ------------o-----------o each resident here moves each resident here moves +1 unit FARTHER (+L) 1 unit CLOSER (-(W - L))Advancing
Xone unit to the right changescost_xby:slope = L - (W - L) = 2 * L - WAs
Xsweeps from left to right,L(the cumulative weight at or left ofX) only grows, soslopetransitions from negative (cost falling), optionally through0(flat tie), to positive (cost rising):- While
2 * L < W: strictly more than half of all residents still sit to the right ofX, soslope < 0and moving right strictly reduces cost. - At the very first settlement coordinate
cwhere2 * L >= W:Lreaches at least half ofW, soslope >= 0fromconward—moving right can never achieve a lower cost!
Thus that first settlement coordinate
cis guaranteed to be an integer and the smallest coordinate achieving the minimum 1D cost! Pay attention to two details in2 * prefix_weight >= total_weight:- Multiplying by
2avoids integer division truncation (5 // 2 == 2would stop early at2 < 2.5). - Using
>=rather than>halts at the left endpoint of a flat tie interval (2 * L == W) instead of crossing to the right endpoint.
- While
Code the 1D weighted median and axis cost
Sort
(coordinate, weight)pairs from left to right, sumtotal_weight, and scan once withprefix_weightto return the first coordinate satisfying2 * prefix_weight >= total_weight. If multiple settlements share coordinatec, sorting groups them together so whichever entry crosses half the total weight still returnsc.def find_lowest_weighted_median(points: List[Tuple[int, int]]) -> int: """Return the smallest coordinate c where cumulative weight <= c is at least half the total.""" # sorted_points: (coordinate, population) pairs ordered left to right, e.g. [(2, 8), (9, 1)]. sorted_points = sorted(points) total_weight = 0 for coord, weight in sorted_points: total_weight += weight # Sweep left to right, accumulating population until we reach or pass 50% of total_weight. prefix_weight = 0 for coord, weight in sorted_points: prefix_weight += weight # Why 2 * prefix_weight >= total_weight: # 1. Multiplying by 2 keeps exact integer arithmetic (avoids odd-number division rounding). # 2. Using >= (not >) stops at the smallest coordinate when a flat interval ties for min cost. if 2 * prefix_weight >= total_weight: return coord return sorted_points[-1][0] def compute_axis_cost(points: List[Tuple[int, int]], meeting_coord: int) -> int: """Return sum of weight * |coord - meeting_coord| along a single 1D axis.""" axis_total = 0 for coord, weight in points: axis_total += weight * abs(coord - meeting_coord) return axis_totalAssemble `min_weighted_manhattan` and trace Example 3
Extract
x_pointsandy_points, solve both axes independently, and sum their optimal travel costs:def min_weighted_manhattan(cities: List[List[int]]) -> List[int]: # Phase 1: Split 2D cities into two independent 1D lists of (coordinate, population) pairs. # x_points, y_points: e.g. [(2, 4), (5, 3), (9, 5)] and [(6, 4), (1, 3), (3, 5)]. x_points: List[Tuple[int, int]] = [] y_points: List[Tuple[int, int]] = [] for x, y, weight in cities: x_points.append((x, weight)) y_points.append((y, weight)) # Phase 2: Minimize East-West and North-South travel independently via weighted medians. best_x = find_lowest_weighted_median(x_points) best_y = find_lowest_weighted_median(y_points) # Phase 3: Sum the optimal x-axis travel cost and y-axis travel cost. total_cost = compute_axis_cost(x_points, best_x) + compute_axis_cost(y_points, best_y) return [total_cost, best_x, best_y]Let's trace Example 3:
cities = [[2, 6, 4], [5, 1, 3], [9, 3, 5]], wheretotal_weight = 4 + 3 + 5 = 12:X-axis sorted pairs: (2, w=4) (5, w=3) (9, w=5) prefix_weight: 4 7 12 2 * prefix >= 12? 8 >= 12 no 14 >= 12 YES! -> best_x = 5 cost_x(5) = 4*|2 - 5| + 3*|5 - 5| + 5*|9 - 5| = 12 + 0 + 20 = 32 Y-axis sorted pairs: (1, w=3) (3, w=5) (6, w=4) prefix_weight: 3 8 12 2 * prefix >= 12? 6 >= 12 no 16 >= 12 YES! -> best_y = 3 cost_y(3) = 4*|6 - 3| + 3*|1 - 3| + 5*|3 - 3| = 12 + 6 + 0 = 18Notice that
(5, 3)is not one of the three input settlements (best_x = 5came from[5, 1, 3]whilebest_y = 3came from[9, 3, 5]), andtotal_cost = 32 + 18 = 50, returning[50, 5, 3].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_lowest_weighted_median(points: List[Tuple[int, int]]) -> int: """Return the smallest coordinate c where cumulative weight <= c is at least half the total.""" # sorted_points: (coordinate, population) pairs ordered left to right, e.g. [(2, 8), (9, 1)]. sorted_points = sorted(points) total_weight = 0 for coord, weight in sorted_points: total_weight += weight # Sweep left to right, accumulating population until we reach or pass 50% of total_weight. prefix_weight = 0 for coord, weight in sorted_points: prefix_weight += weight # Why 2 * prefix_weight >= total_weight: # 1. Multiplying by 2 keeps exact integer arithmetic (avoids odd-number division rounding). # 2. Using >= (not >) stops at the smallest coordinate when a flat interval ties for min cost. if 2 * prefix_weight >= total_weight: return coord return sorted_points[-1][0] def compute_axis_cost(points: List[Tuple[int, int]], meeting_coord: int) -> int: """Return sum of weight * |coord - meeting_coord| along a single 1D axis.""" axis_total = 0 for coord, weight in points: axis_total += weight * abs(coord - meeting_coord) return axis_total def min_weighted_manhattan(cities: List[List[int]]) -> List[int]: # Phase 1: Split 2D cities into two independent 1D lists of (coordinate, population) pairs. # x_points, y_points: e.g. [(2, 4), (5, 3), (9, 5)] and [(6, 4), (1, 3), (3, 5)]. x_points: List[Tuple[int, int]] = [] y_points: List[Tuple[int, int]] = [] for x, y, weight in cities: x_points.append((x, weight)) y_points.append((y, weight)) # Phase 2: Minimize East-West and North-South travel independently via weighted medians. best_x = find_lowest_weighted_median(x_points) best_y = find_lowest_weighted_median(y_points) # Phase 3: Sum the optimal x-axis travel cost and y-axis travel cost. total_cost = compute_axis_cost(x_points, best_x) + compute_axis_cost(y_points, best_y) return [total_cost, best_x, best_y]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine choosing a central station in a grid city of East-West avenues and North-South streets where everyone travels strictly along city blocks—a metric known as Manhattan distance (the grid distance |x1 - x2| + |y1 - y2| summing horizontal and vertical offsets). Because walking East-West never alters how many blocks someone must walk North-South, picking the optimal X coordinate and picking the optimal Y coordinate split into two completely independent 1D tug-of-war problems! Along a single axis, sliding the hub one step right forces every resident behind you to walk 1 block farther while letting every resident ahead of you walk 1 block less, so total travel drops until at least half of all residents sit at or behind you—a balance point called the weighted median (the earliest sorted coordinate where cumulative weight reaches at least 50% of total weight).
Testing every integer location (X, Y) across a 10^6 by 10^6 grid would inspect 10^12 candidates at O(n) work apiece, which times out completely. Computing the population-weighted average (center of mass) also gives the wrong answer because averages minimize squared distances rather than straight absolute distances, allowing one distant town to drag the hub away from where the majority lives.
Here is a quick 3-settlement walkthrough on cities = [[1, 0, 1], [5, 0, 1], [8, 0, 10]] (total_weight = 12):
- Sort
(x, weight)pairs alongX:(1, 1), (5, 1), (8, 10)and maintain a prefix sum (a running total accumulated from left to right):1,2,12. - Stop at the first coordinate satisfying
2 * prefix_weight >= 12:x = 8(2 * 12 = 24 >= 12), givingbest_x = 8andbest_y = 0. - Evaluate travel cost at
(8, 0):1 * 7 + 1 * 3 + 10 * 0 = 10(whereas the unweighted median(5, 0)would cost34!).
Complexity
Let n be the number of settlements (len(cities)).
- Time:
O(n log n). Building(x, w)and(y, w)lists takesO(n), sorting eachn-element axis list takesO(n log n)comparisons, and sweeping for both weighted medians plus computing both axis costs each take a singleO(n)pass. - Space:
O(n). Twon-element lists of(coordinate, weight)pairs (x_pointsandy_points) and their sorted copies infind_lowest_weighted_mediantakeO(n)memory.
Edge cases
- Single settlement (
[[5, 7, 3]]):2 * 3 >= 3holds immediately on the sole entry, returning[0, 5, 7]. - Exact
50% / 50%split ([[1, 3, 2], [5, 3, 2]]): everyXin[1, 5]ties at cost8;2 * prefix_weight >= total_weighttriggers atx = 1(2 * 2 >= 4), choosing the smallestXin lexicographical order (dictionary-style ordering comparingXfirst andYsecond). - Single settlement holding strictly over half of all residents: its
(x, y)is the unique optimal hub regardless of how far away smaller settlements lie. - Optimal
(X, Y)is not an input settlement:best_xcan come from one settlement andbest_yfrom another, as in[[2, 6, 4], [5, 1, 3], [9, 3, 5]]->(5, 3). - Multiple settlements sharing the exact same coordinate: sorting places identical coordinates adjacent to one another, so whichever entry crosses
50%returns that shared coordinate. - 64-bit travel totals:
10^5settlements with weights up to1,000spanning10^6grid units can reach10^14, handled natively by Python's arbitrary-precision integers (useint64_t/longin C++ or Java).
Common mistakes
- Using the unweighted median: ignoring resident counts balances settlement counts rather than people, severely inflating travel when one settlement holds most of the population.
- Using the weighted mean (average):
sum(w * x) / sum(w)minimizessum(w * (x - X)^2)instead ofsum(w * |x - X|), and frequently lands on a non-optimal coordinate for Manhattan travel. - Checking
2 * prefix_weight > total_weightinstead of>=: strict>skips across a50% / 50%flat tie to the largest tied coordinate rather than the smallest, violating tie-breaking on Example 1. - Checking
prefix_weight >= total_weight // 2: floor division truncates5 // 2to2, stopping at2out of5(40%) before reaching half the total weight. - Sorting
citiesonce byxand reusing that order fory:ycoordinates remain unsorted when ordered byx, so each axis must be sorted independently.
Follow-up questions
- Why does axis separation break down under straight-line Euclidean distance, and how would you approximate the best hub then? Under Euclidean distance (straight-line distance
sqrt((x - X)^2 + (y - Y)^2)), the square root couples(x - X)^2and(y - Y)^2inside a non-linear radical, so the 2D objective no longer splits into separateXandYsums. That optimum—the weighted geometric median—has no closed-form formula in general, though because the sum of weighted Euclidean distances is a convex function (a bowl-shaped surface where every local minimum is a global minimum), iterative solvers like Weiszfeld's algorithm or gradient descent converge rapidly to the continuous optimum, after which nearby integer grid candidates can be evaluated. (If squared Euclidean distance were used instead, the square root disappears, the axes decouple again, and the weighted mean minimizes each axis.) - How fast does your algorithm run, and how could you reach linear O(n) time when inputs arrive pre-ordered or unsorted? Sorting
x_pointsandy_pointsdominates the runtime atO(n log n). If separatex-sorted andy-sorted views are already provided, omitting the twosorted()calls drops the runtime directly toO(n). Even on unsorted input, you can achieveO(n)expected time via weighted quickselect (a selection algorithm that partitions around a pivot and recurses only into the side containing the50%weight threshold without fully sorting), orO(n + U)deterministic time by accumulating weights into a bucket array of lengthU + 1whereU = 10^6is the maximum coordinate. - When an entire segment or rectangle of grid coordinates achieves the exact same minimum cost, how do you characterize that region and guarantee the tie-break? Along a single axis, the optimal coordinates always form a closed interval
[lo, hi], wherelois the earliest sorted coordinate with2 * prefix_weight >= total_weightandhiis the earliest sorted coordinate with2 * prefix_weight > total_weight. Whenever no prefix equalstotal_weight / 2exactly,lo == hiand the optimum is unique; when a prefix equalstotal_weight / 2exactly, every coordinate in[lo, hi]has zero slope and identical cost. Combining both axes yields the optimal rectangle[lo_x, hi_x] x [lo_y, hi_y], and stopping on>=guarantees returning its lexicographically smallest corner(lo_x, lo_y).
Follow-up questions
- Why does axis separation break down under straight-line Euclidean distance, and how would you approximate the best hub then?
- How fast does your algorithm run, and how could you reach linear O(n) time when inputs arrive pre-ordered or unsorted?
- When an entire segment or rectangle of grid coordinates achieves the exact same minimum cost, how do you characterize that region and guarantee the tie-break?
Similar questions
- Mismatched Indices in a Height Lineup
- Maximum Subset Gain Under an OR Threshold
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance