Problem Description
Given departure times for a set of buses and arrival times for passengers (all unique), along with a maximum capacity per bus, determine the latest time you can arrive at the bus station (without matching any other passenger’s arrival time) so that you can still catch one of the buses. When a bus departs, it picks up passengers in order of their arrival times (up to its capacity), and you must arrive on or before the bus’s departure time to board it.
Key Insights
- Sort both the bus departure times and passenger arrival times.
- For each bus, simulate the boarding process by assigning the earliest arriving passengers until the capacity is reached or there are no more waiting.
- The target is to determine a time for your arrival such that:
- If the last bus is not full, you can simply arrive at its departure time (unless that time conflicts with a passenger’s arrival).
- If the last bus is full, the candidate time shifts to one less than the arrival time of the last passenger who boarded.
- When choosing your arrival time, ensure it does not match any existing passenger’s arrival time; if it does, decrement until a free time is found.
Space and Time Complexity
Time Complexity: O(n log n + m log m)
Space Complexity: O(1) (ignoring the space required to sort; in-place sorting can be assumed)
Solution
The approach is to simulate the boarding process:
- Sort the bus departure times and passengers’ arrival times.
- Use a pointer to track which passengers have already been processed.
- Iterate through each bus:
- For each bus, board as many passengers as possible (or until the waiting passengers’ arrival time is too late) by moving the pointer.
- For the last bus:
- If it has not reached capacity, set the candidate arrival time to the bus’s departure time.
- If the last bus is full, set the candidate time to be one minute before the last boarded passenger’s arrival time.
- Since you cannot pick a time that coincides with another passenger's, adjust the candidate time downward if needed until you find a valid time.
The primary data structures used are arrays (which are sorted) and simple pointers iterating through these arrays. The main trick is to properly simulate the boarding and then backtrack from candidate time if it collides with any other passenger arrival.