Problem Description
Given a car with a limited seating capacity and an array of trips (each specifying the number of passengers to pick up, the start location, and the drop-off location), determine if the car can pick up and drop off all passengers without exceeding its capacity at any point along its journey eastward.
Key Insights
- Use a sweep-line algorithm by converting each trip into two events: one for picking up passengers (adding to the load) and one for dropping them off (subtracting from the load).
- Sort the events by location. For events occurring at the same location, process drop-offs before pick-ups to free up capacity.
- At each event point, update the current passenger count and verify it does not exceed the car’s capacity.
- This simulation technique efficiently handles overlapping intervals with a difference array concept.
Space and Time Complexity
Time Complexity: O(N log N) due to sorting the events, where N is the number of trips. Space Complexity: O(N) for storing the events.
Solution
The idea is to transform each trip into two events. For each trip:
- Create an event at the 'from' location to add passengers.
- Create an event at the 'to' location to subtract passengers. Sort these events by the location value. When events coincide at the same location, process the drop-off events (negative changes) before the pick-up events (positive changes) to ensure capacity is freed before being assigned. Then, iterate over the sorted events, update the cumulative number of passengers, and check against the available capacity. If at any point the current passenger count exceeds the capacity, return false. If the entire journey is simulated without breaching capacity, return true.