Car Pooling

Decide whether one car with a fixed number of seats can carry every group of passengers on its trip.

A car has capacity empty seats and drives east only, along a road whose locations are numbered 0 to 1000. Each trip in the array trips has the form [numPassengers, from, to]: that many passengers get on at location from and get off at location to. Return true if the car can carry every trip without ever holding more passengers than capacity, and false otherwise.

Example 1
Input: trips = [[2, 1, 5], [3, 3, 7]], capacity = 4
Output: false
Explanation: between locations 3 and 5 there are 2 + 3 = 5 passengers.
Example 2
Input: trips = [[2, 1, 5], [3, 3, 7]], capacity = 5
Output: true
Example 3
Input: trips = [[2, 1, 5], [3, 5, 7]], capacity = 3
Output: true
Explanation: the first group gets off at 5 just as the second gets on.
Solution

The Idea

Think of a shuttle that drives down one long road and picks up groups of people along the way. Each group tells the driver where it gets on and where it gets off. The driver only worries about one thing: is there ever a moment when more people want a seat than the car has?

Take Example 1. Two passengers get on at location 1 and ride to 5. Three more get on at 3 and ride to 7. From 3 until 5, both groups are in the car, so it holds 2 + 3 = 5 people. With 4 seats that does not work, and the answer is false. With 5 seats, as in Example 2, everyone fits.

With two trips this is easy to see. With hundreds of trips that overlap in all sorts of ways, how do we find the busiest stretch of the road without comparing every trip with every other one?

Notice that the number of people in the car only changes where someone gets on or off. In between, it stays the same. So write down, for each location, how much the count changes there: +2 at 1 and -2 at 5 for the first trip, +3 at 3 and -3 at 7 for the second. Then drive from location 0 and keep a running total. Look at the picture below.

Example 1 on a road from location 0 to 7. Trip [2, 1, 5] adds 2 at location 1 and takes 2 away at 5; trip [3, 3, 7] adds 3 at 3 and takes 3 away at 7. Adding up the changes gives 0, 2, 2, 5, 5, 3, 3, 0 passengers in the car, and 5 at locations 3 and 4 is more than the capacity 4.

The two bars at the top are the two trips. The row labelled “change” holds only the numbers we wrote down, and every other location gets 0. The row labelled “in the car” adds those changes up from the left: 0, then 2, 2, then 5 at location 3. The two orange cells, at locations 3 and 4, hold 5 passengers, more than the 4 seats.

A list like the “change” row, which stores how much a count goes up or down at each place instead of the count itself, is called a difference array. Adding its cells up from the start, as the “in the car” row does, is called a prefix sum, and it turns the changes back into the count at every location.

Example 3 shows one more detail. The first group gets off at 5, and the second gets on at 5. Both changes land in the same cell: -2 and +3 make +1, so the count at 5 goes from 2 to 3, never to 5. The people leaving free their seats before the new ones sit down, which is why 3 seats are enough.

Solution Approach

Turning the running total into code starts with a look at the plain way of counting, which is slower, and then settles three things: where to store the changes, what happens at a location where people both get off and get on, and when to stop.

Counting riders at every location

Why not count the riders directly? For each location from 0 to 1000, loop over all the trips and add up the passengers of every trip with from <= location < to. That is 1001 passes over the trips, so with n trips about 1001 × n checks. Writing the changes down instead costs two updates per trip, and one more walk along the road reads off every count.

Storing the changes

Where do the changes go? Locations are whole numbers from 0 to 1000, so an int array with 1001 cells has one cell for each of them. A trip [2, 1, 5] adds 2 to cell 1 and subtracts 2 from cell 5. The trips can come in any order, because adding numbers into cells gives the same totals whatever order they arrive in.

Getting off and on at the same location

At which cell should the passengers leave? A trip covers the road from from up to, but not including, to, since the passengers are out of the car at to. So the subtraction goes into cell to itself. The count is checked once per location, after all its changes are added, so seats freed at a location are already free for anyone getting on there.

Stopping early

When can we answer? As soon as the running total goes above capacity at some location, the answer is false, and the rest of the road does not matter. A total equal to capacity is fine: a full car is still allowed. If the walk reaches the end of the road without going over, the answer is true.

Java Solution

The method carPooling works in these steps:

  1. First, create an int array change with 1001 cells, one for each location from 0 to 1000. Java fills a new array with zeros.
  2. Loop over trips. For each trip, add its passengers, trip[0], to change[trip[1]], the cell where they get on, and subtract them from change[trip[2]], the cell where they get off.
  3. Start a running total inCar at 0. A second loop walks along change from location 0 and adds each cell into inCar, which is then the number of passengers right after that location.
  4. After each addition, if inCar is greater than capacity, return false.
  5. If the second loop reaches location 1000 without going over, return true.

The main method runs the three examples. It then tries three trips, not sorted by start, that fill the car to exactly its 11 seats, and one group of 5 riding from location 0 to 1000 in a 4-seat car.

Java
public class CarPooling {

    public static boolean carPooling(int[][] trips, int capacity) {
        int[] change = new int[1001];          // riders getting on (+) or off (-) at each location
        for (int[] trip : trips) {
            change[trip[1]] += trip[0];        // they get on at "from"
            change[trip[2]] -= trip[0];        // they get off at "to", freeing the seats there
        }
        int inCar = 0;
        for (int delta : change) {
            inCar += delta;                    // passengers in the car after this location
            if (inCar > capacity) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(carPooling(new int[][] {{2, 1, 5}, {3, 3, 7}}, 4));
        System.out.println(carPooling(new int[][] {{2, 1, 5}, {3, 3, 7}}, 5));
        System.out.println(carPooling(new int[][] {{2, 1, 5}, {3, 5, 7}}, 3));
        System.out.println(carPooling(new int[][] {{3, 2, 7}, {3, 7, 9}, {8, 3, 9}}, 11));
        System.out.println(carPooling(new int[][] {{5, 0, 1000}}, 4));
    }
}

Running it prints:

Output
false
true
true
true
false

The first three lines, false, true and true, match Examples 1 to 3. In Example 1, the second loop stops at location 3, where inCar reaches 5 in a 4-seat car.

Look at the fourth line. The trip [8, 3, 9] comes last in the array but starts before [3, 7, 9], and the answer is still right. From location 3 to 7, 3 + 8 = 11 passengers ride, exactly the 11 seats. At 7, three get off and three get on, so the car stays at 11 and never goes over, giving true.

The last line is false because 5 passengers get on at location 0, the very first cell, and the check fails right there. Their drop-off at 1000, the last cell, fits in the array too.

What if the seats were freed one location late, at to + 1, as if passengers rode past their stop? We ran that change on Example 3 and it printed false. At location 5 it still counts the first group of 2 next to the new group of 3, which is 5 passengers in a 3-seat car.

Complexity

The work is two array updates for each trip, plus one walk along the 1001 locations.

  • Time: O(n + L), because each of the n trips costs two updates to change, and the second loop visits each of the L = 1001 locations at most once.
  • Space: O(L), because change has one cell for every possible location, and all trips share those same 1001 cells however many trips there are.

If locations had no small upper limit, an array with one cell per location would be too big. Sorting the pick-up and drop-off events works then, as in Meeting Rooms II.