Car Pooling - Problem
Car Pooling Challenge: You're operating a rideshare service with a car that has a
You have an array of
•
•
•
Your Goal: Determine if you can complete all trips without ever exceeding your car's passenger capacity. Return
Example: With capacity=4 and trips=[[2,1,5],[3,3,7]], you pick up 2 passengers at km 1, then 3 more at km 3 (total 5 > 4), so return
capacity of empty seats. Your car can only drive eastward along a straight highway - no U-turns allowed! You have an array of
trips where each trip is represented as [numPassengers, from, to]:•
numPassengers - number of passengers for this trip•
from - pickup location (km east from starting point)•
to - drop-off location (km east from starting point)Your Goal: Determine if you can complete all trips without ever exceeding your car's passenger capacity. Return
true if possible, false otherwise.Example: With capacity=4 and trips=[[2,1,5],[3,3,7]], you pick up 2 passengers at km 1, then 3 more at km 3 (total 5 > 4), so return
false. Input & Output
example_1.py — Basic Valid Case
$
Input:
trips = [[2,1,5],[3,5,7]], capacity = 5
›
Output:
true
💡 Note:
At km 1, pick up 2 passengers (total: 2). At km 5, drop off 2 passengers and pick up 3 passengers (total: 3). Never exceeds capacity of 5.
example_2.py — Capacity Exceeded
$
Input:
trips = [[2,1,5],[3,3,7]], capacity = 4
›
Output:
false
💡 Note:
At km 1, pick up 2 passengers (total: 2). At km 3, pick up 3 more passengers (total: 5). This exceeds the capacity of 4.
example_3.py — Overlapping Trips
$
Input:
trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
›
Output:
true
💡 Note:
Multiple overlapping trips but total passengers never exceeds 11. Maximum occurs between km 3-7 with 3+8=11 passengers exactly at capacity.
Visualization
Tap to expand
Understanding the Visualization
1
Map the Route
Identify all pickup and dropoff locations along the eastward highway
2
Record Events
At each location, note passenger changes (+pickup, -dropoff)
3
Simulate Journey
Travel chronologically, tracking running passenger count
4
Check Capacity
Ensure passenger count never exceeds car capacity
Key Takeaway
🎯 Key Insight: We only need to check passenger counts at locations where pickups or drop-offs occur, not every single point along the route. This optimization reduces time complexity significantly for large distance ranges.
Time & Space Complexity
Time Complexity
O(n log n)
O(n log n) for sorting events by location, then O(n) to process
⚡ Linearithmic
Space Complexity
O(n)
Map stores at most 2n entries (pickup and drop-off events)
⚡ Linearithmic Space
Constraints
- 1 ≤ trips.length ≤ 1000
- trips[i].length == 3
- 1 ≤ capacity ≤ 105
- 0 ≤ numPassengersi ≤ capacity
- 0 ≤ fromi < toi ≤ 1000
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code