🧠
Sorting Events and Sweep Line
💡 This approach improves efficiency by transforming trips into events and processing them in order, which is a common pattern for interval problems.
Intuition
Convert each trip into two events: passengers getting on and passengers getting off. Sort these events by location and simulate passenger changes in order.
Algorithm
- Create a list of events: (location, passenger change), +num for pickup, -num for dropoff.
- Sort events by location.
- Iterate through events, updating current passengers by event passenger change.
- If current passengers exceed capacity at any point, return false.
- Return true if capacity never exceeded.
💡 This approach reduces complexity by only processing points where passenger count changes, avoiding unnecessary checks.
def carPooling(trips, capacity):
events = []
for num, start, end in trips:
events.append((start, num))
events.append((end, -num))
events.sort()
current_passengers = 0
for _, change in events:
current_passengers += change
if current_passengers > capacity:
return False
return True
# Example usage
if __name__ == '__main__':
print(carPooling([[2,1,5],[3,3,7]], 4)) # False
print(carPooling([[2,1,5],[3,3,7]], 5)) # True
Line Notes
events = []Initialize list to hold all pickup and dropoff events
events.append((start, num))Add pickup event with positive passenger count
events.append((end, -num))Add dropoff event with negative passenger count
events.sort()Sort events by location to process in order
current_passengers += changeUpdate current passengers based on event
if current_passengers > capacity:Check if capacity exceeded after event
import java.util.*;
public class Solution {
public boolean carPooling(int[][] trips, int capacity) {
List<int[]> events = new ArrayList<>();
for (int[] trip : trips) {
events.add(new int[]{trip[1], trip[0]}); // pickup
events.add(new int[]{trip[2], -trip[0]}); // dropoff
}
events.sort((a, b) -> Integer.compare(a[0], b[0]));
int currentPassengers = 0;
for (int[] event : events) {
currentPassengers += event[1];
if (currentPassengers > capacity) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.carPooling(new int[][]{{2,1,5},{3,3,7}}, 4)); // false
System.out.println(sol.carPooling(new int[][]{{2,1,5},{3,3,7}}, 5)); // true
}
}
Line Notes
List<int[]> events = new ArrayList<>();Create list to hold pickup and dropoff events
events.add(new int[]{trip[1], trip[0]});Add pickup event with positive passenger count
events.add(new int[]{trip[2], -trip[0]});Add dropoff event with negative passenger count
events.sort((a, b) -> Integer.compare(a[0], b[0]));Sort events by location ascending
currentPassengers += event[1];Update current passengers after event
if (currentPassengers > capacity)Check if capacity exceeded
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool carPooling(vector<vector<int>>& trips, int capacity) {
vector<pair<int,int>> events;
for (auto& trip : trips) {
events.emplace_back(trip[1], trip[0]); // pickup
events.emplace_back(trip[2], -trip[0]); // dropoff
}
sort(events.begin(), events.end());
int currentPassengers = 0;
for (auto& event : events) {
currentPassengers += event.second;
if (currentPassengers > capacity) {
return false;
}
}
return true;
}
int main() {
vector<vector<int>> trips1 = {{2,1,5},{3,3,7}};
cout << (carPooling(trips1, 4) ? "true" : "false") << endl; // false
cout << (carPooling(trips1, 5) ? "true" : "false") << endl; // true
return 0;
}
Line Notes
vector<pair<int,int>> events;Create vector to hold pickup and dropoff events
events.emplace_back(trip[1], trip[0]);Add pickup event with positive passenger count
events.emplace_back(trip[2], -trip[0]);Add dropoff event with negative passenger count
sort(events.begin(), events.end());Sort events by location ascending
currentPassengers += event.second;Update current passengers after event
if (currentPassengers > capacity)Check if capacity exceeded
function carPooling(trips, capacity) {
const events = [];
for (const [num, start, end] of trips) {
events.push([start, num]); // pickup
events.push([end, -num]); // dropoff
}
events.sort((a, b) => a[0] - b[0]);
let currentPassengers = 0;
for (const [, change] of events) {
currentPassengers += change;
if (currentPassengers > capacity) {
return false;
}
}
return true;
}
// Example usage
console.log(carPooling([[2,1,5],[3,3,7]], 4)); // false
console.log(carPooling([[2,1,5],[3,3,7]], 5)); // true
Line Notes
const events = [];Initialize array to hold pickup and dropoff events
events.push([start, num]);Add pickup event with positive passenger count
events.push([end, -num]);Add dropoff event with negative passenger count
events.sort((a, b) => a[0] - b[0]);Sort events by location ascending
currentPassengers += change;Update current passengers after event
if (currentPassengers > capacity)Check if capacity exceeded
TimeO(n log n) due to sorting events
SpaceO(2n) for events array
We create two events per trip and sort them, then iterate once to check capacity, which is efficient for large inputs.
💡 For n=100,000 trips, sorting 200,000 events is feasible within typical interview time constraints.
Interview Verdict: Accepted / Efficient
This approach is efficient and commonly accepted in interviews for interval capacity tracking problems.