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^5
  • 0 <= x_i, y_i <= 10^6
  • 1 <= w_i <= 1000

Step-by-step walkthrough

  1. Understand the travel formula and tie-breaking rule

    Each settlement is [x, y, w]: its 2D grid position (x, y) and resident count w >= 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] minimizing total_cost(X, Y). Whenever multiple points tie for the lowest cost, we break ties in lexicographical order: pick the smallest X, and among those still tied, pick the smallest Y.

    • Input: 1 <= len(cities) <= 10^5, 0 <= x, y <= 10^6, 1 <= w <= 1,000.
    • Output: [cost, X, Y] as three integers.
  2. 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 evaluate total_cost(X, Y) in O(n) time per point.

    With coordinates up to 10^6, that bounding box holds up to 10^6 * 10^6 = 10^12 grid points, and summing over 10^5 settlements per point would require 10^17 operations. We need a mathematical decomposition.

  3. Split the 2D grid into two independent 1D lines

    Expand each settlement's term w * (|x - X| + |y - Y|) into w * |x - X| + w * |y - Y|. Collecting all x terms together and all y terms together splits total_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 X never alters cost_y(Y), and changing Y never alters cost_x(X). Consequently:

    1. min total_cost(X, Y) = (min over X of cost_x(X)) + (min over Y of cost_y(Y)).
    2. Tie-breaking also decouples cleanly: the smallest X among optimal (X, Y) pairs is simply the smallest X minimizing cost_x(X), and the smallest Y is the smallest Y minimizing cost_y(Y).

    One 2D grid problem reduces to two identical 1D number-line problems!

  4. Find the balance point on a 1D line: the lowest weighted median

    Suppose settlements sit along a single line with total population W. Place X on the far left and slide X rightward by +1 unit 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 X one unit to the right changes cost_x by:

    slope = L - (W - L) = 2 * L - W
    

    As X sweeps from left to right, L (the cumulative weight at or left of X) only grows, so slope transitions from negative (cost falling), optionally through 0 (flat tie), to positive (cost rising):

    • While 2 * L < W: strictly more than half of all residents still sit to the right of X, so slope < 0 and moving right strictly reduces cost.
    • At the very first settlement coordinate c where 2 * L >= W: L reaches at least half of W, so slope >= 0 from c onward—moving right can never achieve a lower cost!

    Thus that first settlement coordinate c is guaranteed to be an integer and the smallest coordinate achieving the minimum 1D cost! Pay attention to two details in 2 * prefix_weight >= total_weight:

    • Multiplying by 2 avoids integer division truncation (5 // 2 == 2 would stop early at 2 < 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.
  5. Code the 1D weighted median and axis cost

    Sort (coordinate, weight) pairs from left to right, sum total_weight, and scan once with prefix_weight to return the first coordinate satisfying 2 * prefix_weight >= total_weight. If multiple settlements share coordinate c, sorting groups them together so whichever entry crosses half the total weight still returns c.

    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
    
  6. Assemble `min_weighted_manhattan` and trace Example 3

    Extract x_points and y_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]], where total_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  = 18
    

    Notice that (5, 3) is not one of the three input settlements (best_x = 5 came from [5, 1, 3] while best_y = 3 came from [9, 3, 5]), and total_cost = 32 + 18 = 50, returning [50, 5, 3].

  7. 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):

  1. Sort (x, weight) pairs along X: (1, 1), (5, 1), (8, 10) and maintain a prefix sum (a running total accumulated from left to right): 1, 2, 12.
  2. Stop at the first coordinate satisfying 2 * prefix_weight >= 12: x = 8 (2 * 12 = 24 >= 12), giving best_x = 8 and best_y = 0.
  3. Evaluate travel cost at (8, 0): 1 * 7 + 1 * 3 + 10 * 0 = 10 (whereas the unweighted median (5, 0) would cost 34!).

Complexity

Let n be the number of settlements (len(cities)).

  • Time: O(n log n). Building (x, w) and (y, w) lists takes O(n), sorting each n-element axis list takes O(n log n) comparisons, and sweeping for both weighted medians plus computing both axis costs each take a single O(n) pass.
  • Space: O(n). Two n-element lists of (coordinate, weight) pairs (x_points and y_points) and their sorted copies in find_lowest_weighted_median take O(n) memory.

Edge cases

  • Single settlement ([[5, 7, 3]]): 2 * 3 >= 3 holds immediately on the sole entry, returning [0, 5, 7].
  • Exact 50% / 50% split ([[1, 3, 2], [5, 3, 2]]): every X in [1, 5] ties at cost 8; 2 * prefix_weight >= total_weight triggers at x = 1 (2 * 2 >= 4), choosing the smallest X in lexicographical order (dictionary-style ordering comparing X first and Y second).
  • 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_x can come from one settlement and best_y from 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^5 settlements with weights up to 1,000 spanning 10^6 grid units can reach 10^14, handled natively by Python's arbitrary-precision integers (use int64_t / long in 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) minimizes sum(w * (x - X)^2) instead of sum(w * |x - X|), and frequently lands on a non-optimal coordinate for Manhattan travel.
  • Checking 2 * prefix_weight > total_weight instead of >=: strict > skips across a 50% / 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 truncates 5 // 2 to 2, stopping at 2 out of 5 (40%) before reaching half the total weight.
  • Sorting cities once by x and reusing that order for y: y coordinates remain unsorted when ordered by x, 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)^2 and (y - Y)^2 inside a non-linear radical, so the 2D objective no longer splits into separate X and Y sums. 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_points and y_points dominates the runtime at O(n log n). If separate x-sorted and y-sorted views are already provided, omitting the two sorted() calls drops the runtime directly to O(n). Even on unsorted input, you can achieve O(n) expected time via weighted quickselect (a selection algorithm that partitions around a pivot and recurses only into the side containing the 50% weight threshold without fully sorting), or O(n + U) deterministic time by accumulating weights into a bucket array of length U + 1 where U = 10^6 is 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], where lo is the earliest sorted coordinate with 2 * prefix_weight >= total_weight and hi is the earliest sorted coordinate with 2 * prefix_weight > total_weight. Whenever no prefix equals total_weight / 2 exactly, lo == hi and the optimum is unique; when a prefix equals total_weight / 2 exactly, 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

Similar questions

More Concentric Ai interview questions

All 3 Concentric Ai questions →