Campus Bikes II - Problem
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
Understanding the Visualization
1
Input
Workers at positions [[0,0],[2,1]] and bikes at [[1,2],[3,3]]
2
Process
Find optimal assignment minimizing total Manhattan distance
3
Output
Minimum possible sum of distances = 6
Key Takeaway
🎯 Key Insight: Use bitmasks to efficiently track bike assignments and memoization to avoid redundant computation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code