0:00 / 0:00

Can one car carry every trip without going over capacity? Mark pickups and drop-offs on a difference array, then sweep the running total.

▼

The problem

LeetCode 1094 (Medium). A car with capacity empty seats drives east only. trips[i] = [numPassengers, from, to]: that many passengers get on at kilometer from and off at kilometer to. Return true if every trip can be taken without ever having more than capacity passengers on board.

Example (LeetCode's, the one animated): trips = [[2,1,5],[3,3,7]], capacity = 4 → false (between km 3 and 5 both trips ride: 2 + 3 = 5 > 4), and the same trips with capacity = 5 → true.

TRY IT ON LEETCODE ▶

The solution

def carPooling(trips, capacity):
    change = [0] * 1001
    for n, start, end in trips:
        change[start] += n
        change[end] -= n
    riders = 0
    for d in change:
        riders += d
        if riders > capacity:
            return False
    return True

Transcript

Car Pooling. A van with a few seats drives east and never turns around. You get a list of trips: how many riders, where they get on, and where they get off. Can the van take every trip without carrying more riders than it has seats?

Two trips. Two riders go from kilometer one to five, and three riders go from three to seven. With four seats, the van is in trouble. Between three and five, both groups are aboard, five riders in four seats. So it's false. With five seats, it's true.

The simple way stops at every kilometer and adds up every trip that covers it. With a thousand trips on a thousand kilometers of road, that's a million additions.

Here's the trick: the number of riders only changes at a stop. So for each trip, write plus the riders where they get on, and minus the riders where they get off. Every trip is written down once.

Now drive east, adding up the changes as you go. That running total is exactly who's on board. If it ever passes the capacity, return false. Where three get off and three get on, the change is zero, as if everyone got off first.

In code, keep a list of a thousand and one changes. For each trip, add the riders at its start and subtract them at its end. Then sweep: add each change to the riders on board, and the moment there are too many, return false. Otherwise, return true.

Let's run it with four seats. Kilometer one: plus two, so two on board. Kilometer three: plus three, so five on board. Five is more than four: false. With five seats, the van keeps going. Kilometer five: minus two, leaving three. Kilometer seven: minus three, leaving none. Never over: true.

Writing the changes is one pass over the trips; the sweep is one pass over the road. That's order n plus L time, and order L space.

Plus where they get on, minus where they get off, one sweep east. That's Car Pooling.