We can simulate the number of passengers in the car at each kilometer using a difference array. For each trip, increase the passenger count at fromi
and decrease it at toi
. Then, iterate through this array to calculate the actual number of passengers at each point, checking if it ever exceeds the capacity.
Time Complexity: O(n + m) where n is the number of trips and m is the max distance (1000).
Space Complexity: O(m) for the difference array.
1def carPooling(trips, capacity):
2 passenger_changes = [0] * 1001
3
4 for num_passengers, start, end in trips:
5 passenger_changes[start] += num_passengers
6 passenger_changes[end] -= num_passengers
7
8 current_passengers = 0
9 for change in passenger_changes:
10 current_passengers += change
11 if current_passengers > capacity:
12 return False
13
14 return True
A list passenger_changes
schema simulates the number of passengers at any point. Passengers are adjusted using trip data, and evaluation ensures that counts remain within limits.
In this approach, we treat each pick-up and drop-off as events. We collect all events, sort them based on location, and then simulate the process of picking up and dropping off passengers by iterating through events in order, checking if it ever exceeds the car's capacity.
Time Complexity: O(n log n), driven by sorting events.
Space Complexity: O(n).
1var carPooling = function(trips, capacity) {
2 let events = [];
3 for (let [numPassengers, from, to] of trips) {
4 events.push([from, numPassengers]); // pickup
5 events.push([to, -numPassengers]); // drop-off
6 }
7
8 events.sort((a, b) => a[0] - b[0]);
9
10 let currentPassengers = 0;
11 for (let [time, change] of events) {
12 currentPassengers += change;
13 if (currentPassengers > capacity) return false;
14 }
15
16 return true;
17};
By cataloging all stated events, sorted iteratively, we measure the dynamic nature of car capacity against a sorted itinerary.