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: 11 passengers (3+8), km 7-9: 11 passengers (3+8). Maximum is 11 which equals 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 INPUT CAR Capacity = 4 Trips Array: Trip 1: [2, 1, 3] 2 passengers: km 1 to km 3 Trip 2: [3, 2, 4] 3 passengers: km 2 to km 4 Timeline (km): 0 1 2 3 4 ALGORITHM STEPS 1 Create Change Array Track passenger changes at each km 2 Process Trips +passengers at from, -at to km: 0 1 2 3 4 change:[0, +2, +3, -2, -3] Trip1: +2@km1, -2@km3 Trip2: +3@km2, -3@km4 3 Running Sum Calculate passengers at each point km: 0 1 2 3 4 total: 0 2 5 3 0 4 Check Capacity If any total > 4: return false FINAL RESULT Passenger Count Over Time 5 4 3 2 1 0 cap=4 0 1 2 3 4 5! At km 2: 5 passengers needed But capacity is only 4 Output: false Capacity Exceeded! Key Insight: Use a difference array to track passenger changes at each kilometer. Add passengers at pickup points, subtract at drop-off points. Then calculate running sum - if it ever exceeds capacity, return false. Time: O(n + max_location), Space: O(max_location). This avoids sorting and simulates the journey. TutorialsPoint - Car Pooling | Optimal Solution (Difference Array)
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