On a campus represented as a 2D grid, there are n workers and m bikes, with n ≤ m. Each worker and bike is a 2D coordinate on this grid.

We need to assign one unique bike to each worker such that the sum of the Manhattan distances between each worker and their assigned bike is minimized.

Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.

The Manhattan distance between two points p1 and p2 is: |p1.x - p2.x| + |p1.y - p2.y|

Input & Output

Example 1 — Basic Case
$ Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: 6
💡 Note: Assign worker at (0,0) to bike at (1,2) with distance 3, and worker at (2,1) to bike at (3,3) with distance 3. Total distance = 3 + 3 = 6.
Example 2 — Multiple Options
$ Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: 4
💡 Note: Optimal assignment: worker (0,0)→bike (1,0) distance 1, worker (1,1)→bike (2,2) distance 2, worker (2,0)→bike (2,1) distance 1. Total = 1+2+1 = 4.
Example 3 — Same Position
$ Input: workers = [[0,0]], bikes = [[0,0],[1,1]]
Output: 0
💡 Note: Worker at (0,0) gets assigned to bike at (0,0) with Manhattan distance 0.

Constraints

  • 1 ≤ workers.length ≤ bikes.length ≤ 12
  • workers[i].length == bikes[j].length == 2
  • 0 ≤ workers[i][0], workers[i][1], bikes[j][0], bikes[j][1] < 1000

Visualization

Tap to expand
Campus Bikes II - DP Solution INPUT 0 1 2 3 W0 W1 B0 B1 Worker Bike workers = [[0,0],[2,1]] bikes = [[1,2],[3,3]] n=2 workers, m=2 bikes Find min sum of distances ALGORITHM STEPS 1 Define State dp[mask] = min distance mask = bikes used (bitmask) 2 Try All Assignments For each worker, try each available bike 3 Compute Manhattan Dist |x1-x2| + |y1-y2| 4 Track Minimum Keep best assignment DP Transitions W0-B0: |0-1|+|0-2| = 3 W0-B1: |0-3|+|0-3| = 6 W1-B0: |2-1|+|1-2| = 2 W1-B1: |2-3|+|1-3| = 3 Best: W0-B0(3) + W1-B1(3) = 6 FINAL RESULT W0 W1 B0 B1 dist=3 dist=3 Output: 6 3 + 3 = 6 Optimal Assignment: W0 --> B0 W1 --> B1 Key Insight: Use bitmask DP where mask represents which bikes are already assigned. For n workers and m bikes, we have 2^m states. Each worker is assigned to an unassigned bike that minimizes total distance. Time: O(n * 2^m * m), Space: O(2^m). The bitmask tracks bike availability efficiently. TutorialsPoint - Campus Bikes II | Dynamic Programming with Bitmask
Asked in
Google 15 Facebook 12 Uber 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen