1094. Car Pooling
Asked at 12Meta42Google30Amazon28Bloomberg18Microsoft16Infosys45Careem89Zepto77Lyft70Paytm61Goldman Sachs50Flipkart43
Problem
A car with capacity empty seats drives east only. trips[i] = [passengers, from, to] picks up passengers at kilometre from and drops them off at to. Decide whether every trip can be served without ever exceeding capacity.
Example: trips = [[2,1,5],[3,3,7]]: capacity = 4 → false; capacity = 5 → true
Constraints: up to 1000 trips; locations ≤ 1000.
Passengers board at from and leave at to: d[from] += n, d[to] −= n. Sweep the locations; if the running load ever exceeds capacity → false.
Complexity: O(trips + max location).
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = [0] * 1001
for n, a, b in trips:
d[a] += n
d[b] -= n
load = 0
for x in d:
load += x
if load > capacity:
return False
return True
assert Solution().carPooling([[2, 1, 5], [3, 3, 7]], 4) is False
assert Solution().carPooling([[2, 1, 5], [3, 3, 7]], 5) is True
assert Solution().carPooling([[2, 1, 5], [3, 5, 7]], 3) is True
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
int[] d = new int[1001];
for (int[] t : trips) { d[t[1]] += t[0]; d[t[2]] -= t[0]; }
int load = 0;
for (int x : d) if ((load += x) > capacity) return false;
return true;
}
}
func carPooling(trips [][]int, capacity int) bool {
d := make([]int, 1001) // passenger change at each location
for _, t := range trips {
d[t[1]] += t[0]
d[t[2]] -= t[0] // they leave at t[2], before anyone boards there
}
load := 0
for _, x := range d {
load += x
if load > capacity {
return false
}
}
return true
}