Car Pooling (LeetCode 1094): Solution and Explanation

Medium
Array
Sorting
Heap
Simulation
Prefix Sum

A car with capacity seats drives east only. Each trip [num, from, to] has num passengers riding from location from to location to. Return true if the car can serve every trip without ever holding more than capacity passengers.

Intuition

The question is really about one number: the most passengers in the car at the same moment. If that peak fits within capacity, every trip can be served, because the car drives east and picks up and drops off in location order anyway.

Computing the load at every location by adding up every trip that covers it works, but it costs trips times distance. Notice instead that the load only changes at a handful of points. At from it jumps up by num, and at to it drops by num. Everywhere else it stays flat.

So write down only the changes: change[from] += num and change[to] -= num. This is a difference array. A running sum over it from west to east rebuilds the exact load at every location, and you can check it against capacity as you go.

Drop-offs at location x happen before pick-ups at x, so a trip ending at 5 and another starting at 5 never share seats. Netting both into the same change[5] captures exactly that.

Approach: Difference array sweep

  1. Create change, an array of 1001 zeros, one slot per location.
  2. For each trip [num, from, to], add num to change[from] and subtract num from change[to].
  3. Sweep locations 0 to 1000 with a running load, adding change[stop] at each one.
  4. If load ever exceeds capacity, return false.
  5. If the sweep finishes, return true.

Step-by-step example

trips = [[2,1,5],[3,3,7]], capacity = 4
  1. Trip 1 adds +2 at location 1 and -2 at location 5.
  2. Trip 2 adds +3 at location 3 and -3 at location 7.
  3. Sweep: at location 1 the load becomes 2, which fits.
  4. At location 3 the load becomes 2 + 3 = 5, which is more than 4.
  5. Return false. Both groups would be in the car between locations 3 and 5.

Code: Python, Java, C++

1class Solution:
2    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
3        change = [0] * 1001
4        for num, start, end in trips:
5            change[start] += num
6            change[end] -= num
7        load = 0
8        for stop in range(1001):
9            load += change[stop]
10            if load > capacity:
11                return False
12        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Difference array sweep O(n + L)
Sort events O(n log n)
Sort by start with a min-heap of drop-offs O(n log n)
Time

O(n + L)

Each of the n trips writes two entries, then one sweep covers the L = 1001 locations.

Space

O(L)

The change array has one slot per location, independent of the number of trips.

Other approaches

Sort events (time O(n log n), space O(n))

Turn each trip into two events, (from, +num) and (to, -num), sort them by location with drop-offs first on ties, and sweep. It does not depend on the location range, which helps when locations can be huge.

Sort by start with a min-heap of drop-offs (time O(n log n), space O(n))

Process trips by pick-up location and keep a min-heap of active trips keyed by drop-off. Before each pick-up, pop every trip that has already ended and give back its seats. It is the same idea as Meeting Rooms II.

Common mistakes

  • Treating to as still occupied. Passengers leave at to, so the subtraction goes at to, not to + 1.
  • Sorting events with pick-ups before drop-offs at the same location, which counts seats that are already free.
  • Checking only the load at trip start points of the input order rather than sweeping in location order.
  • Sizing the array by the number of trips instead of by the largest location.

Frequently asked questions

Why is checking the peak load enough?

The car only drives east, so it meets every pick-up and drop-off in location order. The only way to fail is to need more seats than exist at some location, which is exactly when the running load exceeds capacity.

What happens when one trip ends where another starts?

Their changes cancel in the same slot, so the load does not spike. That matches the rules: the first group gets off before the second gets on.

When should I use event sorting instead of the array?

If locations could be up to 10^9, a 1001-slot array no longer works. Sorting the 2n events handles any range in O(n log n).

What is the time complexity of Car Pooling?

O(n + L) with the difference array, where L = 1001 is the number of locations, and O(L) extra space.