Python 1094.py
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
delta = defaultdict(int)
for t in trips:
delta[t[1]] += t[0]
delta[t[2]] -= t[0]
have = 0
for d in sorted(delta):
have += delta[d]
if have > capacity:
return False
return True
Difficulty
and has an acceptance rate of about 56% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Heap (Priority Queue)
- Prefix Sum
- Simulation
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a set of car-pooling trips can be accommodated within a vehicle of a given passenger capacity. It does this by converting each trip into a series of passenger count changes at specific locations, then iterating through those changes in order to track the number of passengers on board at any point. If the running total ever exceeds the vehicle’s capacity, the function returns False; otherwise it returns True after processing all locations.
Delta Map Construction
The first logical block creates a mapping from location points to the net change in passenger count that occurs at those points. For each trip, the number of passengers to be picked up is added at the start location and subtracted at the end location.
delta = defaultdict(int)
for t in trips:
delta[t[1]] += t[0] # pick-up at start location
delta[t[2]] -= t[0] # drop-off at end location
This approach collapses overlapping trips into a single structure, allowing the algorithm to consider only the moments when the passenger count actually changes.
Accumulating Passenger Count
After the delta map is built, the code iterates over the sorted location keys. By processing the locations in ascending order, the algorithm simulates the journey from the earliest pick-up point to the latest drop-off point, updating a running total of passengers on board.
have = 0
for d in sorted(delta):
have += delta[d]
if have > capacity:
return False
return True
The variable have represents the current number of passengers. The early return on capacity breach ensures that the function stops as soon as an infeasible condition is detected.
Edge Cases Handled
The algorithm naturally handles trips that start and end at the same location because the net change at that point will be zero, leaving the passenger count unchanged. It also correctly processes trips that share start or end points; the cumulative delta at a shared location aggregates all pick-ups and drop-offs, preserving the correct passenger total. Situations where the list of trips is empty are covered as the loop over sorted(delta) simply does not execute, and the function returns True because no capacity violation can occur.
Performance Optimizations
The use of a defaultdict(int) for the delta map eliminates the need for explicit existence checks when updating counts, reducing overhead in the construction phase. By storing only the points where changes occur, the algorithm avoids iterating over every possible location between the minimum and maximum stops, which could be large. Sorting the keys of the delta map is the only operation that introduces ordering, and it operates on a set whose size is bounded by twice the number of trips (each trip contributes at most two distinct points). The early exit on capacity overflow prevents unnecessary processing of remaining locations once a violation is found, further improving runtime in worst-case scenarios where the capacity is exceeded early.
ELI5 - Simplified Explanation
Imagine a big bus going on a long road trip. Some passengers get on at certain stops and get off at other stops. The code keeps track of how many people are on the bus at any moment.
First, the computer looks at every journey in the list. When a group of people starts their trip, it adds them to a tally for that stop. When that same group reaches their destination, it subtracts them from the tally because they leave the bus.
After noting all the changes at every stop, the computer lines up all the stops in order from the very beginning to the very end. It goes to the first stop and checks how many passengers are on board. It continues to the next stop, adding the people who just got on and taking away the people who just got off.
At every stop along the way, the computer checks to see if there are too many people sitting on the bus. If the number of passengers is bigger than the number of seats available, the bus is too crowded.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | JS | Java | C# | Go | Rust | TS | |
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 253: Meeting Rooms II
Solved On The Same Day
- problem 680: Valid Palindrome II
- problem 478: Generate Random Point in a Circle
- problem 497: Random Point in Non-overlapping Rectangles
- problem 519: Random Flip Matrix
- problem 581: Shortest Unsorted Continuous Subarray
- problem 659: Split Array into Consecutive Subsequences
- problem 738: Monotone Increasing Digits
- problem 743: Network Delay Time
- problem 769: Max Chunks To Make Sorted
- problem 985: Sum of Even Numbers After Queries
- problem 1048: Longest String Chain
- problem 1324: Print Words Vertically
- problem 1680: Concatenation of Consecutive Binary Numbers
- problem 1823: Find the Winner of the Circular Game
- problem 1860: Incremental Memory Leak
- problem 1922: Count Good Numbers
- problem 2487: Remove Nodes From Linked List
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
- problem 517: Super Washing Machines
- problem 632: Smallest Range Covering Elements from K Lists
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality