![]() |
VOOZH | about |
On a campus represented on the X-Y, there are n workers and m bikes (n <= m). You are given:
Assign a bike to each worker by pairing the worker and bike with the shortest Manhattan distance between them. If there are multiple pairs with the same distance, choose the pair with the smallest worker index, and if still tied, choose the pair with the smallest bike index. Return an array answer of length n, where answer[i] is the 0-indexed index of the bike assigned to the ith worker.
Note: The Manhattan distance between two points p1 and p2 is |p1.x - p2.x| + |p1.y - p2.y|.
Example:
Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: [1,0]
Explanation: Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: [0,2,1]
Explanation: Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is [0,2,1].
Approach:
We want to organize the (worker, bike) pairs in ascending order, prioritizing their Manhattan distance, then worker index, and then bike index. Therefore, we will generate all possible (worker, bike) pairs and sort them according to the previously listed priorities. We will then iterate over the pairs, if both the worker and bike are available, assign the bike to the worker, and mark them both as unavailable. We will repeat this process until all workers have been assigned a bike.
Steps-by-step approach:
Below is the implementation of the above approach:
Worker assignments (bike index for each worker): 1 0
Time complexity: O(NMlog(NM)), Here, N is the number of workers, and M is the number of bikes.
Auxiliary Space: O(NM)