Minimum Manhattan Assignment Distance

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

On a 2D integer coordinate grid, n analysts (analysts[i] = [ax, ay]) need equipment from m available field devices (devices[j] = [dx, dy]), where 1 <= n <= 10 and n <= m <= 15.

Every analyst must be paired with one unique device, and no device may be shared between two analysts (when m > n, the remaining m - n devices stay unassigned). Pairing analyst i at [ax, ay] with device j at [dx, dy] incurs their rectilinear (Manhattan) travel distance:

|ax - dx| + |ay - dy|

Implement minimize_total_assignment_distance(analysts, devices) to compute and return the smallest possible sum of Manhattan distances across all n paired analysts.

Examples

Example 1

Input: analysts = [[1, 2], [4, 1]], devices = [[1, 0], [5, 1], [8, 6]]
Output: 3

Pairing analyst 0 ([1, 2]) with device 0 ([1, 0]) costs |1 - 1| + |2 - 0| = 2, and pairing analyst 1 ([4, 1]) with device 1 ([5, 1]) costs |4 - 5| + |1 - 1| = 1, while device 2 ([8, 6]) goes unused. No other distinct pairing achieves a total below 2 + 1 = 3.

Example 2

Input: analysts = [[2, 1], [4, 1]], devices = [[3, 1], [-1, 1]]
Output: 4

If analyst 0 ([2, 1]) took the nearby device 0 ([3, 1], distance 1), analyst 1 ([4, 1]) would have to walk to device 1 ([-1, 1], distance 5), totaling 6. Giving device 1 to analyst 0 (distance 3) and device 0 to analyst 1 (distance 1) achieves the optimal sum 4.

Example 3

Input: analysts = [[-2, 3]], devices = [[4, 1], [0, -1]]
Output: 6

The single analyst at [-2, 3] is |-2 - 4| + |3 - 1| = 8 steps from [4, 1] and |-2 - 0| + |3 - (-1)| = 6 steps from [0, -1], so choosing device 1 yields 6.

Constraints

  • 1 <= n <= 10, where n = len(analysts)
  • n <= m <= 15, where m = len(devices)
  • Each element of analysts and devices is a 2-element integer coordinate [x, y] (coordinates may be negative, zero, or positive, and multiple points may share the same location).

Step-by-step walkthrough

  1. Restate the problem and distance metric

    We are given n analysts (1 <= n <= 10) and m devices (n <= m <= 15) as [x, y] coordinates on a 2D grid. Every analyst must receive one distinct device, while m - n leftover devices (if m > n) remain unused.

    Assigning analyst i at (ax, ay) to device j at (dx, dy) costs their Manhattan distance — the grid-walking distance measured along horizontal and vertical steps only (|ax - dx| + |ay - dy|), with no diagonal shortcuts:

    Analyst at (1, 2), Device at (5, 1):
      |1 - 5| + |2 - 1| = 4 horizontal steps + 1 vertical step = 5
    

    We want the minimum total Manhattan distance summed across all n analysts.

  2. Why greedy rules fail

    Before building a full search, let's check whether a simple greedy algorithm (making whichever single choice looks cheapest right now without looking ahead) works. Two natural greedy ideas both break on just two analysts along a single line:

    Trap 1 — "Each analyst in order grabs their nearest free device":
      Points on x-axis:   D1(0) -------- A0(2) -- A1(3),D0(3)
      Greedy:  A0 grabs D0(3) for cost 1 -> forces A1(3) to walk back to D1(0) for cost 3 -> total = 4
      Optimal: A0 takes D1(0) for cost 2, A1 takes D0(3) for cost 0                       -> total = 2
    
    Trap 2 — "Repeatedly pair the globally closest analyst and device":
      Points on x-axis:   A0(0) -------- D0(2) -- A1(3) -------- D1(5)
      Greedy:  closest pair is A1(3)-D0(2) (cost 1) -> forces A0(0)-D1(5) (cost 5)        -> total = 6
      Optimal: A0(0)-D0(2) (cost 2) + A1(3)-D1(5) (cost 2)                                -> total = 4
    

    Grabbing a cheap match early can strand a later analyst far away, so we must reason about combinations of assignments.

  3. Collapse repeated brute-force states into subsets

    Brute force tries every ordered choice of n distinct devices out of m. For n = 10 and m = 15, there are 15 * 14 * 13 * ... * 6 = 10,897,286,400 permutations — roughly 10.9 billion checks, which is far too slow.

    Look closely at why brute force wastes time. Suppose we assign analysts in fixed order A0, A1, A2, ... and compare two ways of assigning the first two analysts to devices {D3, D7}:

    Option 1: A0 -> D3, A1 -> D7   (say cost = 9)
    Option 2: A0 -> D7, A1 -> D3   (say cost = 5)
                                          |
      For A2 .. A(n-1), BOTH options leave the exact same free devices (all except {D3, D7})!
      Option 1 can NEVER beat Option 2 from here onward, so we only keep cost = 5 for {D3, D7}.
    

    That observation gives us dynamic programming (DP) — solving each distinct subproblem once and storing its best answer in a table so we never recompute it. Instead of tracking who got which device, we only need to remember which subset of devices is currently used! With m <= 15, there are only 2^15 = 32,768 subsets of devices.

  4. Encode device subsets as a bitmask

    A bitmask packs a subset of {0, 1, ..., m - 1} into the binary bits of a plain integer mask, where bit j is 1 if device j is already taken and 0 if device j is still free:

    Example with m = 3 devices (bits written D2 D1 D0):
      mask = 0  (binary 000) -> {}          (0 bits set -> next to assign is Analyst 0)
      mask = 1  (binary 001) -> {D0}        (1 bit  set -> next to assign is Analyst 1)
      mask = 5  (binary 101) -> {D0, D2}    (2 bits set -> next to assign is Analyst 2)
    

    Notice a neat bonus: because we always assign analysts in index order 0, 1, ..., n - 1, if mask has k bits set to 1 (its popcount, meaning the count of 1-bits in binary), then analysts 0 .. k - 1 have already been assigned and analyst k is automatically the next one to place! We do not even need a separate DP dimension for the analyst index.

    Three tiny bit operations handle everything we need: - mask & (1 << j): non-zero if device j is already used in mask, 0 if device j is free. - mask | (1 << j): a new mask with device j added to the used set. - used_count[mask] = used_count[mask >> 1] + (mask & 1): counts 1-bits by shifting off the rightmost bit (mask >> 1) and adding that rightmost bit (mask & 1).

  5. Precompute pairwise costs and bit counts

    Before running the DP, we build the num_analysts x num_devices Manhattan distance table cost so the inner loop never repeats coordinate math, and we precompute used_count[mask] for all 2^m masks:

    def manhattan_distance(point_a: List[int], point_b: List[int]) -> int:
        """Return |ax - bx| + |ay - by| between two [x, y] grid points."""
        return abs(point_a[0] - point_b[0]) + abs(point_a[1] - point_b[1])
    

    Inside minimize_total_assignment_distance, we precompute both tables first:

        num_analysts = len(analysts)
        num_devices = len(devices)
    
        # Phase 1: Precompute all pairwise distances so the DP inner loop does O(1) lookups.
        # cost[i][j]: Manhattan distance from analyst i to device j (num_analysts x num_devices).
        cost: List[List[int]] = []
        for i in range(num_analysts):
            row: List[int] = []
            for j in range(num_devices):
                row.append(manhattan_distance(analysts[i], devices[j]))
            cost.append(row)
    
        # Phase 2: Precompute how many devices are turned on in each m-bit integer mask.
        # used_count[mask]: number of 1-bits in mask = index of the next analyst to assign.
        total_masks = 1 << num_devices
        used_count = [0] * total_masks
        for mask in range(1, total_masks):
            used_count[mask] = used_count[mask >> 1] + (mask & 1)
    
  6. Fill the DP table in one pass and trace Example 1

    Let min_cost[mask] hold the minimum total distance to assign the first used_count[mask] analysts to the exact devices in mask. We start with min_cost[0] = 0 and all other entries at inf.

    Why can we simply loop for mask in range(total_masks): from 0 upward? Because turning a 0-bit into a 1-bit (next_mask = mask | (1 << device_idx)) always increases the integer value (next_mask > mask). Every smaller mask that can feed into mask has already finished before our loop reaches mask!

    When used_count[mask] == num_analysts, every analyst has a device: we update best_total and continue without adding more devices. (Be careful: when m > n, m - n devices stay unused, so the answer is the minimum across masks with n set bits, not min_cost[total_masks - 1]!)

        # Phase 3: Bitmask DP over subsets of used devices.
        # min_cost[mask]: minimum distance to assign analysts 0 .. (used_count[mask] - 1)
        # to the exact subset of devices whose bits are 1 in mask.
        inf = float("inf")
        min_cost = [inf] * total_masks
        min_cost[0] = 0
        best_total = inf
    
        # Turning on a free device bit always creates next_mask > mask, so scanning
        # masks 0 .. total_masks - 1 guarantees min_cost[mask] is final when we read it.
        for mask in range(total_masks):
            current_cost = min_cost[mask]
            if current_cost == inf:
                continue
    
            analyst_idx = used_count[mask]
            # Stop extending once all num_analysts have devices (when m > n, the remaining
            # m - n devices stay unused, so the all-1s mask is never reached).
            if analyst_idx == num_analysts:
                if current_cost < best_total:
                    best_total = current_cost
                continue
    
            # Try giving analyst_idx any device j whose bit is still 0 in mask.
            for device_idx in range(num_devices):
                if mask & (1 << device_idx):
                    continue
                next_mask = mask | (1 << device_idx)
                candidate_cost = current_cost + cost[analyst_idx][device_idx]
                if candidate_cost < min_cost[next_mask]:
                    min_cost[next_mask] = candidate_cost
    
        return int(best_total)
    

    Let's trace Example 1 (analysts = [[1, 2], [4, 1]], devices = [[1, 0], [5, 1], [8, 6]]):

    Pairwise cost[i][j]:          D0(1,0)   D1(5,1)   D2(8,6)
      A0(1,2)                        2         5        11
      A1(4,1)                        4         1         9
    
    DP progression (bits = D2 D1 D0, n = 2):
      mask 0 (000), k=0 -> place A0:
        + D0 -> min_cost[001] = 0 + 2  = 2
        + D1 -> min_cost[010] = 0 + 5  = 5
        + D2 -> min_cost[100] = 0 + 11 = 11
    
      mask 1 (001), k=1 -> place A1:
        + D1 -> min_cost[011] = min(inf, 2 + 1) = 3
        + D2 -> min_cost[101] = min(inf, 2 + 9) = 11
    
      mask 2 (010), k=1 -> place A1:
        + D0 -> min_cost[011] = min(3,   5 + 4) = 3   (keeps cheaper 3!)
        + D2 -> min_cost[110] = min(inf, 5 + 9) = 14
    
      mask 3 (011), k=2 == n -> complete! best_total = min(inf, 3) = 3
      mask 4 (100), k=1 -> updates 101 to min(11, 15)=11 and 110 to min(14, 12)=12
      mask 5 (101), k=2 == n -> complete! best_total = min(3, 11) = 3
      mask 6 (110), k=2 == n -> complete! best_total = min(3, 12) = 3
      mask 7 (111), unreached (inf) -> skipped
    
    Returns 3 (A0 -> D0 for 2, A1 -> D1 for 1).
    
  7. Complete solution

    Putting the distance helper, precomputation tables, and forward bitmask DP loop together gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def manhattan_distance(point_a: List[int], point_b: List[int]) -> int:
        """Return |ax - bx| + |ay - by| between two [x, y] grid points."""
        return abs(point_a[0] - point_b[0]) + abs(point_a[1] - point_b[1])
    
    
    def minimize_total_assignment_distance(analysts: List[List[int]], devices: List[List[int]]) -> int:
        num_analysts = len(analysts)
        num_devices = len(devices)
    
        # Phase 1: Precompute all pairwise distances so the DP inner loop does O(1) lookups.
        # cost[i][j]: Manhattan distance from analyst i to device j (num_analysts x num_devices).
        cost: List[List[int]] = []
        for i in range(num_analysts):
            row: List[int] = []
            for j in range(num_devices):
                row.append(manhattan_distance(analysts[i], devices[j]))
            cost.append(row)
    
        # Phase 2: Precompute how many devices are turned on in each m-bit integer mask.
        # used_count[mask]: number of 1-bits in mask = index of the next analyst to assign.
        total_masks = 1 << num_devices
        used_count = [0] * total_masks
        for mask in range(1, total_masks):
            used_count[mask] = used_count[mask >> 1] + (mask & 1)
    
        # Phase 3: Bitmask DP over subsets of used devices.
        # min_cost[mask]: minimum distance to assign analysts 0 .. (used_count[mask] - 1)
        # to the exact subset of devices whose bits are 1 in mask.
        inf = float("inf")
        min_cost = [inf] * total_masks
        min_cost[0] = 0
        best_total = inf
    
        # Turning on a free device bit always creates next_mask > mask, so scanning
        # masks 0 .. total_masks - 1 guarantees min_cost[mask] is final when we read it.
        for mask in range(total_masks):
            current_cost = min_cost[mask]
            if current_cost == inf:
                continue
    
            analyst_idx = used_count[mask]
            # Stop extending once all num_analysts have devices (when m > n, the remaining
            # m - n devices stay unused, so the all-1s mask is never reached).
            if analyst_idx == num_analysts:
                if current_cost < best_total:
                    best_total = current_cost
                continue
    
            # Try giving analyst_idx any device j whose bit is still 0 in mask.
            for device_idx in range(num_devices):
                if mask & (1 << device_idx):
                    continue
                next_mask = mask | (1 << device_idx)
                candidate_cost = current_cost + cost[analyst_idx][device_idx]
                if candidate_cost < min_cost[next_mask]:
                    min_cost[next_mask] = candidate_cost
    
        return int(best_total)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine handing out m equipment lockers along city blocks to n analysts arriving one after another (A0, then A1, ..., A(n-1)), where walking cost is Manhattan distance (horizontal blocks plus vertical blocks: |ax - dx| + |ay - dy|). Suppose A0 and A1 end up taking lockers {D0, D1}: for A2 and everyone waiting behind them, it makes zero difference whether A0 took D0 and A1 took D1 or the other way around — either way, the exact same set {D0, D1} is locked and unavailable! That lets us use dynamic programming (DP) (solving each distinct subproblem once and saving its best result in a table) indexed by a bitmask (an m-bit integer where bit j is 1 if device j is taken and 0 if free). Even better, the popcount of mask (the number of 1-bits in mask) tells us how many devices have been handed out so far, which automatically equals the index of the next analyst waiting in line.

Why do simpler approaches fail? A greedy algorithm (picking whichever pair looks closest right now without looking ahead) gets trapped easily: in Example 2 (analysts = [[2, 1], [4, 1]], devices = [[3, 1], [-1, 1]]), if A0 at (2, 1) grabs D0 at (3, 1) for cost 1, A1 at (4, 1) is forced all the way back to D1 at (-1, 1) for cost 5 (total 6), whereas swapping gives 3 + 1 = 4. On the other hand, brute-force trying every ordered permutation of n = 10 devices out of m = 15 checks 15! / 5! = 10,897,286,400 assignments, whereas collapsing identical device subsets leaves at most 2^15 = 32,768 states.

Let's trace Example 2 (analysts = [[2, 1], [4, 1]] and devices = [[3, 1], [-1, 1]], n = 2, m = 2, bits D1 D0):

Costs:   cost[A0][D0] = 1,  cost[A0][D1] = 3
         cost[A1][D0] = 1,  cost[A1][D1] = 5

mask = 00 (0 bits -> place A0):
  give D0 -> min_cost[01] = 0 + 1 = 1
  give D1 -> min_cost[10] = 0 + 3 = 3

mask = 01 (1 bit  -> place A1):
  give D1 -> min_cost[11] = min(inf, 1 + 5) = 6

mask = 10 (1 bit  -> place A1):
  give D0 -> min_cost[11] = min(6,   3 + 1) = 4   <- beats greedy's 6!

mask = 11 (2 bits == n -> complete):
  best_total = 4 -> returns 4

Complexity

Let n be the number of analysts (1 <= n <= 10) and m be the number of devices (n <= m <= 15).

  • Time: O(2^m * m + n * m). Building the n x m distance table takes n * m constant-time coordinate subtractions, building used_count loops over 2^m masks in O(1) per mask, and the DP visits each of the 2^m masks at most once while testing up to m device bits per mask. At the maximum size n = 10, m = 15, only 223,695 inner transitions run (well under a millisecond in C, a few milliseconds in Python).
  • Space: O(2^m + n * m). Both min_cost and used_count store one entry for each of the 2^m masks (32,768 entries at m = 15), and cost stores n * m integers (<= 150 entries).

Edge cases

  • Single analyst (n = 1): Masks with 1 bit correspond to giving A0 each single device, so best_total cleanly equals the minimum distance to any device.
  • Surplus devices (m > n): m - n devices remain unused; complete assignments sit at masks with used_count[mask] == n, while the all-ones mask (1 << m) - 1 stays inf.
  • Exact device count (m == n): Every device is used, and (1 << m) - 1 is the sole mask with n set bits.
  • Duplicate coordinates: Two analysts or two devices sharing [x, y] produce 0 distance, and the bitmask still enforces that each physical device index j is used at most once.
  • Negative or large coordinates: abs(ax - dx) + abs(ay - dy) works across negative quadrants, and Python integers have arbitrary precision so distances never overflow.

Common mistakes

  • Reading min_cost[(1 << m) - 1] at the end: When m > n, we stop extending masks as soon as n analysts are placed, so (1 << m) - 1 is never reached and still holds inf. Always take the minimum across masks where used_count[mask] == n.
  • Using a greedy assignment: Assigning each analyst to their nearest unused device, or sorting all (analyst, device) pairs by distance and matching greedily, fails whenever an early saving forces a much larger detour later.
  • Forgetting if mask & (1 << device_idx): continue: Skipping the bit test lets two analysts claim the same device device_idx, leaving next_mask with one fewer set bit than expected and corrupting used_count[next_mask].
  • Computing Euclidean distance instead of Manhattan distance: Using sqrt((ax - dx)^2 + (ay - dy)^2) or squared distance violates the grid distance formula specified in the prompt.

Alternative approaches

  • Bitmask over analysts (O(m * 2^n * n)): Instead of masking the m devices, sweep through devices 0 .. m - 1 one by one and maintain dp[analyst_mask] over the 2^n <= 1,024 subsets of served analysts (each device is either skipped or assigned to one unserved analyst). When n is much smaller than m, 2^n uses far less memory than 2^m.
  • Hungarian algorithm (O(n^2 * m)): Also called Kuhn-Munkres, this classic bipartite matching algorithm (pairing items from two disjoint groups at minimum total weight) solves rectangular n x m cost matrices in polynomial time, scaling effortlessly to n, m ~ 1,000.
  • Min-cost max-flow: Model a directed network from a source to all n analysts (capacity 1, cost 0), from every analyst i to every device j (capacity 1, cost cost[i][j]), and from every device to a sink (capacity 1, cost 0), then push n units of minimum-cost flow.

Follow-up questions

  • How would you solve this problem if both n and m grew up to 1,000? Exponential 2^m (or 2^n) bitmask DP becomes infeasible past ~22 items because every additional item doubles the state space. You would switch to the polynomial-time Hungarian algorithm in O(n^2 * m) time and O(n * m) memory (in Python's scientific stack, scipy.optimize.linear_sum_assignment(cost) solves rectangular cost matrices directly).
  • How can you reconstruct the optimal (analyst, device) pairing instead of returning only the minimum cost? Maintain a parallel array chosen_device = [-1] * total_masks (plus best_mask = -1); whenever candidate_cost < min_cost[next_mask], record chosen_device[next_mask] = device_idx. Afterward, start at mask = best_mask and step backward n times: j = chosen_device[mask] gives the device assigned to analyst used_count[mask] - 1, and clearing that bit via mask ^= (1 << j) moves to the predecessor state.
  • What changes if each device has capacity c >= 1 and can be shared by up to c analysts? When c is small and n <= 10, mask the analysts instead of the devices (2^n <= 1,024 states) and process each device j up to c times so a single device can cover up to c distinct analyst bits. For large n and m, build a min-cost max-flow network and increase each device -> sink edge capacity from 1 to c.

Follow-up questions

Similar questions

More Dark Alpha Capital interview questions

All 1 Dark Alpha Capital questions →