Car Pooling Problem
Description
LeetCode Problem 1094.
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity and an array trips where trips[i] = [numPassengers_i, from_i, to_i] indicates that the i^th trip has numPassengers_i passengers and the locations to pick them up and drop them off are from_i and to_i respectively. The locations are given as the number of kilometers due east from the car's initial location.
Passengers are dropped off before new passengers are picked up at the same location. At every point along the route, the total number of passengers in the car must not exceed capacity.
Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Explanation:
At kilometer 1, 2 passengers are picked up, so the car holds 2.
At kilometer 3, 3 more are picked up, so the car holds 5.
Since 5 > capacity = 4, the trips cannot all be completed.
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Explanation:
At kilometer 1, the car holds 2 passengers.
At kilometer 3, the car holds 5 passengers.
At kilometer 5, the first 2 are dropped off, so the car holds 3.
At kilometer 7, the last 3 are dropped off, so the car holds 0.
The maximum occupancy is 5, which never exceeds capacity = 5.
Constraints:
1 <= trips.length <= 1000trips[i].length == 31 <= numPassengers_i <= 1000 <= from_i < to_i <= 10001 <= capacity <= 10^5
Solution
Approach: Difference Array
We only need to know the number of passengers in the car at every kilometer, and kilometers go only up to 1000. A trip [p, from, to] adds p passengers on the stretch from .. to-1.
Adding p to each kilometer of every trip would be slow, so use a difference array instead: diff[from] += p and diff[to] -= p. Walking diff from left to right with a running sum then gives the exact load at each kilometer. If the load ever goes above capacity, the answer is false.
The tricky case is a stop where one group gets off and another gets on. Passengers are dropped off before new ones are picked up, so the trip is over at to, not after it. That is why the -p goes on diff[to] itself: at that kilometer the leaving and the arriving passengers are added up together, and the leaving ones are never counted twice.
Complexity: O(n + M) time and O(M) space, where n is the number of trips and M = 1001 is the number of kilometers.
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
# diff[x] = change in the number of passengers at kilometer x
diff = [0] * 1001
for passengers, start, end in trips:
diff[start] += passengers
diff[end] -= passengers # dropped off at `end`, before anyone is picked up there
load = 0
for change in diff:
load += change
if load > capacity:
return False
return True