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, wheren = len(analysts)n <= m <= 15, wherem = len(devices)- Each element of
analystsanddevicesis 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
Restate the problem and distance metric
We are given
nanalysts (1 <= n <= 10) andmdevices (n <= m <= 15) as[x, y]coordinates on a 2D grid. Every analyst must receive one distinct device, whilem - nleftover devices (ifm > n) remain unused.Assigning analyst
iat(ax, ay)to devicejat(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 = 5We want the minimum total Manhattan distance summed across all
nanalysts.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 = 4Grabbing a cheap match early can strand a later analyst far away, so we must reason about combinations of assignments.
Collapse repeated brute-force states into subsets
Brute force tries every ordered choice of
ndistinct devices out ofm. Forn = 10andm = 15, there are15 * 14 * 13 * ... * 6 = 10,897,286,400permutations — 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 only2^15 = 32,768subsets of devices.Encode device subsets as a bitmask
A bitmask packs a subset of
{0, 1, ..., m - 1}into the binary bits of a plain integermask, where bitjis1if devicejis already taken and0if devicejis 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, ifmaskhaskbits set to1(its popcount, meaning the count of1-bits in binary), then analysts0 .. k - 1have already been assigned and analystkis 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 devicejis already used inmask,0if devicejis free. -mask | (1 << j): a new mask with devicejadded to the used set. -used_count[mask] = used_count[mask >> 1] + (mask & 1): counts1-bits by shifting off the rightmost bit (mask >> 1) and adding that rightmost bit (mask & 1).Precompute pairwise costs and bit counts
Before running the DP, we build the
num_analysts x num_devicesManhattan distance tablecostso the inner loop never repeats coordinate math, and we precomputeused_count[mask]for all2^mmasks: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)Fill the DP table in one pass and trace Example 1
Let
min_cost[mask]hold the minimum total distance to assign the firstused_count[mask]analysts to the exact devices inmask. We start withmin_cost[0] = 0and all other entries atinf.Why can we simply loop
for mask in range(total_masks):from0upward? Because turning a0-bit into a1-bit (next_mask = mask | (1 << device_idx)) always increases the integer value (next_mask > mask). Every smaller mask that can feed intomaskhas already finished before our loop reachesmask!When
used_count[mask] == num_analysts, every analyst has a device: we updatebest_totalandcontinuewithout adding more devices. (Be careful: whenm > n,m - ndevices stay unused, so the answer is the minimum across masks withnset bits, notmin_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).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 then x mdistance table takesn * mconstant-time coordinate subtractions, buildingused_countloops over2^mmasks inO(1)per mask, and the DP visits each of the2^mmasks at most once while testing up tomdevice bits per mask. At the maximum sizen = 10, m = 15, only223,695inner transitions run (well under a millisecond in C, a few milliseconds in Python). - Space:
O(2^m + n * m). Bothmin_costandused_countstore one entry for each of the2^mmasks (32,768entries atm = 15), andcoststoresn * mintegers (<= 150entries).
Edge cases
- Single analyst (
n = 1): Masks with1bit correspond to givingA0each single device, sobest_totalcleanly equals the minimum distance to any device. - Surplus devices (
m > n):m - ndevices remain unused; complete assignments sit at masks withused_count[mask] == n, while the all-ones mask(1 << m) - 1staysinf. - Exact device count (
m == n): Every device is used, and(1 << m) - 1is the sole mask withnset bits. - Duplicate coordinates: Two analysts or two devices sharing
[x, y]produce0distance, and the bitmask still enforces that each physical device indexjis 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: Whenm > n, we stop extending masks as soon asnanalysts are placed, so(1 << m) - 1is never reached and still holdsinf. Always take the minimum across masks whereused_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 devicedevice_idx, leavingnext_maskwith one fewer set bit than expected and corruptingused_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 themdevices, sweep through devices0 .. m - 1one by one and maintaindp[analyst_mask]over the2^n <= 1,024subsets of served analysts (each device is either skipped or assigned to one unserved analyst). Whennis much smaller thanm,2^nuses far less memory than2^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 rectangularn x mcost matrices in polynomial time, scaling effortlessly ton, m ~ 1,000. - Min-cost max-flow: Model a directed network from a source to all
nanalysts (capacity1, cost0), from every analystito every devicej(capacity1, costcost[i][j]), and from every device to a sink (capacity1, cost0), then pushnunits 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(or2^n) bitmask DP becomes infeasible past~22items because every additional item doubles the state space. You would switch to the polynomial-time Hungarian algorithm inO(n^2 * m)time andO(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(plusbest_mask = -1); whenevercandidate_cost < min_cost[next_mask], recordchosen_device[next_mask] = device_idx. Afterward, start atmask = best_maskand step backwardntimes:j = chosen_device[mask]gives the device assigned to analystused_count[mask] - 1, and clearing that bit viamask ^= (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
cis small andn <= 10, mask the analysts instead of the devices (2^n <= 1,024states) and process each devicejup toctimes so a single device can cover up tocdistinct analyst bits. For largenandm, build a min-cost max-flow network and increase eachdevice -> sinkedge capacity from1toc.
Follow-up questions
- How would you solve this problem if both n and m grew up to 1,000?
- How can you reconstruct the optimal (analyst, device) pairing instead of returning only the minimum cost?
- What changes if each device has capacity c >= 1 and can be shared by up to c analysts?
Similar questions
- 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
- Increment Digit Array