Campus Bikes - Problem
Imagine you're managing a bike-sharing program on a university campus! ๐ดโโ๏ธ You have n workers who need bikes and m bikes scattered across campus (where n โค m). Your job is to efficiently assign one bike to each worker.
The assignment follows a greedy strategy: always pick the worker-bike pair with the shortest Manhattan distance first. If there's a tie in distance, prioritize by smallest worker index, then by smallest bike index.
Manhattan Distance Formula:
Goal: Return an array where
The assignment follows a greedy strategy: always pick the worker-bike pair with the shortest Manhattan distance first. If there's a tie in distance, prioritize by smallest worker index, then by smallest bike index.
Manhattan Distance Formula:
|x1 - x2| + |y1 - y2|Goal: Return an array where
result[i] is the index of the bike assigned to the i-th worker. Input & Output
example_1.py โ Basic Assignment
$
Input:
workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
โบ
Output:
[1, 0]
๐ก Note:
Worker 0 is at (0,0) and Worker 1 is at (2,1). Distances: W0โB0=3, W0โB1=6, W1โB0=2, W1โB1=2. Smallest distance is 2 (tie between W1โB0 and W1โB1). Choose W1โB0 (smaller bike index). Then W0โB1. Result: [1,0].
example_2.py โ Tie-breaking by Worker Index
$
Input:
workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
โบ
Output:
[0, 2, 1]
๐ก Note:
Multiple pairs have distance 1: W0โB0=1, W1โB2=1. W0 has smaller index, so W0โB0 first. Then W2โB1=1 is smallest remaining. Finally W1โB2. Result: [0,2,1].
example_3.py โ Single Worker-Bike Pair
$
Input:
workers = [[0,0]], bikes = [[1,1]]
โบ
Output:
[0]
๐ก Note:
Only one worker and one bike available. Worker 0 gets assigned to Bike 0 (the only option). Manhattan distance is |0-1| + |0-1| = 2.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Distances
Compute Manhattan distance between every worker-bike pair
2
Sort by Priority
Order pairs by distance (asc), worker index (asc), bike index (asc)
3
Greedy Assignment
Pick the best available pair and assign, marking both as used
4
Repeat Until Complete
Continue until all workers have bikes assigned
Key Takeaway
๐ฏ Key Insight: The greedy strategy works because we always make the locally optimal choice (shortest distance with proper tie-breaking), which leads to the globally optimal assignment for this problem.
Time & Space Complexity
Time Complexity
O(nm log(nm))
Generate nm pairs O(nm), sort them O(nm log(nm)), assign O(nm) - dominated by sorting
โก Linearithmic
Space Complexity
O(nm)
Store all worker-bike pairs for sorting
โก Linearithmic Space
Constraints
- n == workers.length
- m == bikes.length
- 1 โค n โค m โค 1000
- workers[i].length == bikes[j].length == 2
- 0 โค workers[i][0], workers[i][1], bikes[j][0], bikes[j][1] < 1000
- All worker and bike positions are unique.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code