sagelearnai

Car Pooling

Difficulty: Medium · Pattern: Intervals · LeetCode #1094

A car with capacity empty seats drives only east. trips[i] = [numPassengers, from, to] picks people up at from and drops them off at to. Return true if every trip can be completed without ever going over capacity.

Examples

text
trips = [[2,1,5],[3,3,7]], capacity = 4  →  false   (5 people between km 3 and 5)
trips = [[2,1,5],[3,3,7]], capacity = 5  →  true
trips = [[2,1,5],[3,5,7]], capacity = 3  →  true    (drop-off at 5 happens before pickup at 5)

Hints

  1. The load only changes at pickup and drop-off points.
  2. Locations are ≤ 1000, so a difference array works: diff[from] += p, diff[to] -= p.

Approach

Record +p at from and −p at to in a difference array, then take a running prefix sum. If the sum ever exceeds capacity, return false. Drop-offs at to are applied at index to before anyone boards there, which matches the "drop off first" semantics, since both updates go into the same cell.

For large coordinates, use sorted events instead (O(n log n)). It's the same sweep-line idea as Meeting Rooms II.

Complexity

Time: O(n + L) where L = max location. Space: O(L).

Python solution
def carPooling(trips, capacity):
    diff = [0] * 1002
    for p, a, b in trips:
        diff[a] += p
        diff[b] -= p
    load = 0
    for d in diff:
        load += d
        if load > capacity:
            return False
    return True
JavaScript solution
function carPooling(trips, capacity) {
  const diff = new Array(1002).fill(0);
  for (const [p, a, b] of trips) { diff[a] += p; diff[b] -= p; }
  let load = 0;
  for (const d of diff) { load += d; if (load > capacity) return false; }
  return true;
}