SDE & MLE Prep

1094. Car Pooling

Problem

A car with capacity empty seats drives east only. trips[i] = [passengers, from, to] picks up passengers at kilometre from and drops them off at to. Decide whether every trip can be served without ever exceeding capacity.

Example: trips = [[2,1,5],[3,3,7]]: capacity = 4 → false; capacity = 5 → true

Constraints: up to 1000 trips; locations ≤ 1000.

Passengers board at from and leave at to: d[from] += n, d[to] −= n. Sweep the locations; if the running load ever exceeds capacity → false.

Complexity: O(trips + max location).

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        d = [0] * 1001
        for n, a, b in trips:
            d[a] += n
            d[b] -= n
        load = 0
        for x in d:
            load += x
            if load > capacity:
                return False
        return True