![]() |
VOOZH | about |
Given an array workers[] and bikes[], which represents position of workers and bikes on a 2D plane, the task is to assign each worker to a bike based on the shortest Manhattan distance between them. If multiple pairs share the same distance then prioritize by worker's index and then by bike index. Provide a list showing which bike is assigned to a worker.
Note: The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
Constraints: 1 <= workers.length <= bike.length <= 10
Example:
Input: workers = {{0,0},{2,1}}, bikes = {{1,2},{3,3}}
Output: {1,0}
Explanation: Worker 1 selects Bike 0 as it is the closest without ties, and Worker 0 is assigned Bike 1.Input: workers = {{0,0},{1,1},{2,0}}, bikes = {{1,0},{2,2},{2,1}}
Output: {0,2,1}
Explanation: Worker 0 chooses Bike 0 initially. Worker 1 and Worker 2 have the same distance to Bike 2, so Worker 1 is assigned to Bike 2, and Worker 2 takes Bike 1.
Approach:
This approach use dp with bitmasking technique to keep track of which bikes have been assigned to workers. Bitmasking is a way to use bits to represent a set of items. In this case, each bit in an integer represents a package.
Now, for each driver, starting from the first one, we go through the bikes and assign an available package to the driver. We can check if a package is available by looking at the corresponding bit in our integer. If the bit is 0, the package is available.
When we assign a package to a driver, we need to mark it as unavailable for the other workers. We do this by changing the corresponding bit in our integer from 0 to 1.
In this approach, we use bitwise operations to check, set, and unset bits in our integer. Here’s how:
- Bitwise AND(&) : We can use this operation to check if a bit is set(1). If the result of bitmask & (1 << i) is not 0, then the ith bit is set.
- Bitwise OR(|) : We can use this operation to set a bit(make it 1).The expression bitmask | (1 << i) will set the ith bit.
- Bitwise XOR(^) : We can use this operation to unset a bit(make it 0).The expression bitmask ^ (1 << i) will unset the ith bit if it is set.
Steps-by-step approach:
Below are the implementation of the above approach:
6
Time Complexity: O(2^n * n^2), where n is the maximum number of packages (10 in this case).
Auxiliary space: O(2^n), where n is the maximum number of packages (10 in this case).