Problem Statement
Given a list of trips [numPassengers, from, to] and a car with a fixed capacity, determine whether the car can make every pickup and drop-off along the route without ever exceeding capacity.
Input
trips— each entry[p, s, e]picks upppassengers at locations, drops them off at locatione.capacity— integer seat capacity.
trips = [[2,1,5],[3,3,7]], capacity = 4Output
A boolean: true if the trip sequence is feasible, false if capacity is exceeded at any point.
falseConstraints
1 ≤ trips.length ≤ 10000 ≤ trips[i][0] ≤ 100(passengers per trip)0 ≤ trips[i][1] < trips[i][2] ≤ 1000(locations)1 ≤ capacity ≤ 10⁵
Intuition
Two interchangeable lenses — both are sweep-line at heart:
- Sweep line: each trip produces a
+pevent at pickup and a-pevent at drop-off. Sort events by location, sweep, reject as soon as the running load exceedscapacity. - Difference array: because locations are bounded
0…1000, use a fixed arraydiff[], dodiff[s] += panddiff[e] -= pinO(1), then prefix-sum the array to get the load at every point.
diff after updates: [0, +2, 0, +3, 0, -2, 0, -3, 0, …]
Prefix sums: [0, 2, 2, 5, 5, 3, 3, 0, …]
↑ exceeds capacity 4 → return falseSolution
def carPooling(trips: list[list[int]], capacity: int) -> bool:
events = []
for p, s, e in trips:
events.append((s, p))
events.append((e, -p))
events.sort()
cur = 0
for _, delta in events:
cur += delta
if cur > capacity:
return False
return Truedef carPooling(trips: list[list[int]], capacity: int) -> bool:
diff = [0] * 1001 # locations 0..1000
for p, s, e in trips:
diff[s] += p
diff[e] -= p
cur = 0
for d in diff:
cur += d
if cur > capacity:
return False
return Truefunction carPooling(trips: number[][], capacity: number): boolean {
const diff = new Array(1001).fill(0);
for (const [p, s, e] of trips) {
diff[s] += p;
diff[e] -= p;
}
let cur = 0;
for (const d of diff) {
cur += d;
if (cur > capacity) return false;
}
return true;
}Complexity
| Metric | Value | Reason |
|---|---|---|
| Time (sweep) | O(n log n) | Sorting 2n events |
| Time (diff array) | O(n + max) | Linear over trips + fixed-size array walk |
| Space | O(n) / O(max) | Events list or fixed-size buffer |
Edge Case Thinking
| Scenario | Handling |
|---|---|
Single trip with p ≤ capacity | Peak load = p → always true. |
Overlap exactly at drop-off [_, 1, 5] & [_, 5, 10] | Drop-off processed before pickup at location 5 → load is released first. |
| Diff-array scaling | Falls back to sweep line when coordinates exceed 1000. |
| Reject early | Diff-array version can short-circuit as soon as cur > capacity. |
Passenger count 0 | No-op — events cancel; doesn’t affect feasibility. |
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.