Algo-Sim › Intervals

Car Pooling (Difference Array)

Medium · Intervals · step through it in Java, Python and C++ on your own input

The line-sweep idea on an array: mark +p where a trip starts and −p where it ends, then one running sum gives the load at every stop.

Problem

A car with capacity empty seats drives east only. trips[i] = [passengers, from, to] picks up that many passengers at kilometre from and drops them at to. Return true if every trip can be served without ever exceeding the capacity.

Constraints

Edge cases to test

Follow-up questions

What if stop numbers are huge?
Sort the +p and −p events (or use a sorted map) instead of an array indexed by stop: O(n log n).
What is the difference-array trick in general?
Add +v at the start and −v after the end; one prefix sum then applies every range update: O(n + range).

Solution

Java

public boolean carPooling(int[][] trips, int capacity) {
    int[] diff = new int[1001];
    for (int[] t : trips) {
        diff[t[1]] += t[0];   // they get in at from
        diff[t[2]] -= t[0];   // and out at to
    }
    int load = 0;
    for (int x = 0; x < diff.length; x++) {
        load += diff[x];
        if (load > capacity) return false;
    }
    return true;
}

Python

def car_pooling(trips, capacity):
    diff = [0] * 1001
    for people, start, end in trips:
        diff[start] += people  # they get in at start
        diff[end] -= people    # and out at end
    load = 0
    for x in range(len(diff)):
        load += diff[x]
        if load > capacity:
            return False
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool carPooling(vector<vector<int>> &trips, int capacity) {
        vector<int> diff = vector<int>(1001);
        for (vector<int> &t : trips) {
            diff[t[1]] += t[0]; // they get in at from
            diff[t[2]] -= t[0]; // and out at to
        }
        int load = 0;
        for (int x = 0; x < int(diff.size()); x++) {
            load += diff[x];
            if (load > capacity)
                return false;
        }
        return true;
    }
};

More Intervals problems