#1094
Car Pooling
MediumArraySortingHeap (Priority Queue)SimulationPrefix SumSweep LineSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a sweep line technique where we treat each trip as two events: a pickup and a drop-off. By sorting these events, we can efficiently track the number of passengers in the car at any point.
⚙️
Algorithm
3 steps- 1Step 1: Create an array of events where each trip generates two events: one for pickup and one for drop-off.
- 2Step 2: Sort the events first by location, then by type (pickup before drop-off).
- 3Step 3: Traverse through the sorted events, adjusting the current passenger count and checking against the capacity.
solution.py14 lines
1# Full working Python code
2
3def carPooling(trips, capacity):
4 events = []
5 for num_passengers, from_loc, to_loc in trips:
6 events.append((from_loc, num_passengers)) # pickup
7 events.append((to_loc, -num_passengers)) # drop-off
8 events.sort()
9 current_passengers = 0
10 for _, change in events:
11 current_passengers += change
12 if current_passengers > capacity:
13 return False
14 return Trueℹ
Complexity note: The time complexity is O(n log n) due to the sorting of events, while the space complexity is O(n) for storing the events.
- 1Using a sweep line technique can significantly reduce complexity.
- 2Sorting events allows us to process pickups and drop-offs in a single pass.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.