Car Polling
Complete Date: 2020-09-21
Description
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location]
contains information about the i
-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true
if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11Output: true
Constraints
trips.length <= 1000trips[i].length == 31 <= trips[i][0] <= 1000 <= trips[i][1] < trips[i][2] <= 10001 <= capacity <= 100000
Sort the pickup and dropoff events by location, then process them in order.
Solution
A simple idea is to go through from the start to end, and check if the actual capacity exceeds capacity.
To know the actual capacity, we just need the number of passengers changed at each timestamp.
We can save the number of passengers changed at each time, sort it by timestamp, and finally iterate it to check the actual capacity.
var carPooling = function (trips, capacity) {const locations = {};trips.forEach(([numPassengers, start, end]) => {locations[start] = (locations[start] || 0) + numPassengers;locations[end] = (locations[end] || 0) - numPassengers;});for (const v of Object.values(locations)) {if (v) {capacity -= v;}if (capacity < 0) return false;}return true;};
Complexity Analysis
Assume N is the length of trips.
Time complexity: O(Nlog(N)) since we need to iterate over trips and sort our timestamp. Iterating costs O(N), and sorting costs Nlog(N), and adding together we have O(N) + Nlog(N) =O(Nlog(N)).
Space complexity: O(N) since in the worst case we need O(N) to store timestamp.