Car Pooling
Medium
Topics
There is a car with capacity empty seats, driving east and never turning around. You are given trips, where trips[i] = [numPassengers, from, to] means the i-th trip picks up numPassengers at kilometre from and drops them at kilometre to.
Return true if every trip can be made without ever exceeding capacity.
Example 1
false. A drop-off frees its seats before a pick-up at the same kilometre.[numPassengers, from, to], positioned by from and to.Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false Explanation: Between kilometre 3 and 5 the car would hold 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 leaves at kilometre 5 exactly as the second boards.
Constraints
- 1 <= trips.length <= 1000
- trips[i].length == 3
- 1 <= numPassengers <= 100
- 0 <= from < to <= 1000
- 1 <= capacity <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
The car only moves forward, so the whole journey is one pass along the kilometre axis. What matters at any point is the number of passengers on board, and that only changes at a pick-up or a drop-off.
A drop-off at the same kilometre as a pick-up frees the seats first — the passengers are gone by the time the next group boards — which is the detail the third example turns on.
Approach
- Record the change in occupancy at each kilometre:
+numPassengersatfromand-numPassengersatto. - Walk the kilometres in increasing order, keeping a running total of those changes.
- That running total is the number on board over the stretch beginning at that kilometre. If it ever exceeds
capacity, answerfalse. - Surviving the whole axis answers
true. Processing drops before pick-ups at the same kilometre falls out naturally, because both land on the same bucket and sum before being compared.
Walkthrough
trips = [[2,1,5],[3,3,7]], capacity = 4
km: 1 3 5 7
delta: +2 +3 -2 -3
onboard: 2 5 <- exceeds 4 -> falseComplexity
- Time — O(n + K): one pass over the trips to record the changes, then one pass over the fixed kilometre range K.
- Space — O(K): one bucket per kilometre. Sorting the events instead uses O(n).
Common Pitfalls
- Treating a drop-off at kilometre
xas happening after a pick-up atxwrongly rejects trips that hand over seats exactly on the boundary. - The capacity is a limit on passengers on board at one time, not on the total carried over the journey.
Full Solution — all languages
class Solution:
def carPooling(self, matrix, target):
deltas = {}
for passengers, start, end in matrix:
deltas[start] = deltas.get(start, 0) + passengers
deltas[end] = deltas.get(end, 0) - passengers
onboard = 0
for stop in sorted(deltas):
onboard += deltas[stop]
if onboard > target:
return False
return Trueimport java.util.*;
class Solution {
public boolean carPooling(int[][] matrix, int target) {
TreeMap<Integer, Integer> deltas = new TreeMap<>();
for (int[] trip : matrix) {
deltas.merge(trip[1], trip[0], Integer::sum);
deltas.merge(trip[2], -trip[0], Integer::sum);
}
int onboard = 0;
for (int delta : deltas.values()) {
onboard += delta;
if (onboard > target) return false;
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool carPooling(vector<vector<int>>& matrix, int target) {
map<int, int> deltas;
for (auto& trip : matrix) {
deltas[trip[1]] += trip[0];
deltas[trip[2]] -= trip[0];
}
int onboard = 0;
for (auto& kv : deltas) {
onboard += kv.second;
if (onboard > target) return false;
}
return true;
}
};/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/ var carPooling = function(matrix, target) {
const deltas = new Map();
for (const trip of matrix) {
deltas.set(trip[1], (deltas.get(trip[1]) || 0) + trip[0]);
deltas.set(trip[2], (deltas.get(trip[2]) || 0) - trip[0]);
}
let onboard = 0;
for (const stop of [...deltas.keys()].sort((a, b) => a - b)) {
onboard += deltas.get(stop);
if (onboard > target) return false;
}
return true;
};