Car Pooling

Determine if all pickups can fit under capacity using a delta-array sweep on locations.

Medium
Time O(n + L) Space O(L)
LeetCode
3 min read
intervals difference-array sweep

Problem#

A car has capacity seats. trips[i] = [passengers, from, to] means passengers people get on at from and off at to. Return true iff capacity is never exceeded.

Examples#

  • trips = [[2,1,5],[3,3,7]], capacity = 4false
  • trips = [[2,1,5],[3,3,7]], capacity = 5true

Constraints#

  • 1 <= trips.length <= 1000, 0 <= from < to <= 1000.

Approach#

Difference array on locations: delta[from] += passengers, delta[to] -= passengers. Sweep and accumulate; any prefix sum > capacity is a fail.

Solution#

Car Pooling
class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
int delta[1001] = {0};
for (auto& t : trips) {
delta[t[1]] += t[0];
delta[t[2]] -= t[0];
}
int cur = 0;
for (int x : delta) {
cur += x;
if (cur > capacity) return false;
}
return true;
}
};

Editorial#

Difference arrays convert “add X to range [l, r)” from O(r - l) to O(1) per operation, with a single O(L) sweep at the end. Note delta[t[2]] -= passengers (passengers leave exactly at the destination — the trip is [from, to) in this problem’s semantics, so they shouldn’t count at index to).

Complexity#

  • Time: O(n + L).
  • Space: O(L).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.