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] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively.

The locations are given as the number of kilometers due east from the car's initial location.

Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.

Input & Output

Example 1 — Exceeds Capacity
$ Input: trips = [[2,1,3],[3,2,4]], capacity = 4
Output: false
💡 Note: At kilometer 2, we have 2 passengers from trip 1 and 3 passengers from trip 2, totaling 5 passengers which exceeds capacity 4.
Example 2 — Within Capacity
$ Input: trips = [[2,1,3],[3,2,4]], capacity = 5
Output: true
💡 Note: Maximum passengers at any point is 5 (at km 2), which equals the capacity, so it's possible.
Example 3 — Sequential Trips
$ Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
💡 Note: At km 3-7: 8 passengers, km 7-9: 3 passengers. Maximum is 8 which is less than capacity 11.

Constraints

  • 1 ≤ trips.length ≤ 1000
  • trips[i].length == 3
  • 1 ≤ numPassengersi ≤ 100
  • 0 ≤ fromi < toi ≤ 1000
  • 1 ≤ capacity ≤ 100000

Visualization

Tap to expand
Car Pooling Problem Overviewtrips = [[2,1,3],[3,2,4]], capacity = 4KM 0KM 1KM 2KM 3KM 40 passengers2 passengers5 passengers3 passengers0 passengersTrip 1: [2,1,3]2 passengers, km 1→3Trip 2: [3,2,4]3 passengers, km 2→4Capacity: 4, Peak: 5 passengers at km 2Result: false (exceeds capacity)
Understanding the Visualization
1
Input
Trips with pickup/dropoff locations and capacity limit
2
Process
Track passenger count at each location
3
Output
Return true if capacity never exceeded
Key Takeaway
🎯 Key Insight: Track cumulative passenger changes at pickup/dropoff points rather than checking every location individually
Asked in
Uber 45 Lyft 38 Amazon 32 Google 28
32.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen