Statement▼
You are given a car with a fixed number of seats, denoted by an integer capacity
. The car only travels in one direction — eastward — and does not make any U-turns.
You are also provided with an array, trips
, where each element trips[i]
Your task is to determine whether it is possible to complete all the trips without exceeding the car’s capacity at any point in time.
Return TRUE if all trips can be completed successfully, or FALSE otherwise.
Constraints:
1≤ trips.length
≤1000 trips[i].length
==3 1≤numPassengersi≤100 0≤fromi<toi≤1000 1≤ capacity
≤105
Solution
The core intuition behind this solution is to simulate the journey of the car using a timeline, tracking when passengers get in and get out. This approach aligns with the merge intervals pattern, where we focus on events happening at specific points in time, rather than handling each trip separately in isolation. The idea is to accumulate and monitor the number of passengers in the car at any moment using a difference array (also known as a prefix sum technique).
In the context of this problem, each trip defines a passenger change over a specific interval — passengers are picked up at
This strategy is built on two key observations:
Each trip contributes a net passenger change at exactly two locations:
Increase at the pickup location (
from )Decrease at the drop-off location (
to )
The car’s capacity must never be exceeded at any point on the journey, so we monitor the cumulative passenger count as we move forward in time.
This strategy leverages the difference array pattern, which is a version of merge intervals. Rather than merging overlapping intervals explicitly, it simulates all trips together via a timeline of passenger changes.
Let’s break down the steps:
A list
timestamp
of size1001 (based on constraints) is created to track changes in passenger counts at each kilometer point.For each trip
[numPassengersi,fromi,toi] intrips
:Add
numPassengers
attimestamp[
fromi ]
Subtract
numPassengers
attimestamp[
toi ]
This marks the start and end of each passenger interval without iterating over the full range.
To simulate the trip and track capacity, initialize a variable
used_capacity = 0
.Iterate through the
timestamp
list, adding the passenger changes at each point. If at any pointused_capacity > capacity
, return FALSE immediately— the car is overloaded.If the full timeline is processed without exceeding capacity, return TRUE, indicating that all trips can be accommodated.
Let’s look at the following illustration to get a better understanding of the solution: