Problem Description
Given positions of workers and bikes on a 2D plane, assign each worker a bike. Choose the (worker, bike) pair with the smallest Manhattan distance. When distances are tied, assign the pair with the smallest worker index first, and if still tied, assign the one with the smallest bike index. Continue this process until every worker has a bike, and return the bike index assigned to each worker.
Key Insights
- Compute the Manhattan distance between every worker and bike pair.
- To achieve the tie-breaking rules, sort all pairs by distance, then by worker index and bike index.
- Once a worker is assigned a bike, skip any other pairs involving that worker or the already assigned bike.
- The problem can also be approached using bucket sort because the Manhattan distance range is limited, but sorting is intuitive given the constraints.
Space and Time Complexity
Time Complexity: O(n * m * log(n * m)) where n is the number of workers and m is the number of bikes. Space Complexity: O(n * m) for storing all worker-bike pairs.
Solution
Create all possible (worker, bike) pairs along with their Manhattan distances. Sort this list of pairs by:
- Manhattan distance,
- Worker index (if distances are equal),
- Bike index (if both distance and worker index are equal).
Then, iterate over the sorted list and assign bikes to workers if neither the worker nor the bike has already been assigned. This guarantees that at each step, the optimal available pairing (according to the problem’s requirements) is made. This method naturally enforces the tie-breaking rules specified in the problem.