Python 0853.py
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
fleets = len(position)
cars = sorted(zip(position, speed), reverse = True)
arrive = [ (target - p) / s for p, s in cars ] # time of arrival
incoming = 0 # time of arrival of current fleet
for a in arrive:
if a <= incoming: # bump into one of the cars ahead
fleets -= 1
else:
incoming = a # leader of a new fleet
return fleets
Difficulty
and has an acceptance rate of about 55% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Monotonic Stack
- Sorting
- Stack
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 Solution class implements a method carFleet that computes the number of car fleets that will arrive at a destination point target. A fleet is defined as a group of cars that travel together because a faster car catches up to a slower one ahead of it and then moves at the slower car’s speed. The algorithm processes the positions and speeds of the cars, determines the arrival times, and merges cars into fleets when appropriate.
Key Steps
The method begins by initializing a counter for the total number of fleets based on the number of cars supplied:
fleets = len(position)
Next, the positions and speeds are paired and sorted in descending order of position. Sorting in reverse order ensures that the cars are examined from the one closest to the target to the one farthest away:
cars = sorted(zip(position, speed), reverse=True)
For each car, the time required to reach the target is calculated. This is done by subtracting the car’s current position from the target distance and dividing by its speed:
arrive = [(target - p) / s for p, s in cars]
A variable incoming is used to keep track of the arrival time of the leading car of the current fleet. It is initially set to zero, indicating that no fleet has been established yet:
incoming = 0
The algorithm then iterates over the list of arrival times. For each arrival time a, it checks whether the car would catch up to the fleet ahead. If the current car’s arrival time is less than or equal to incoming, it means the car will merge with the fleet ahead, and the total fleet count is decremented. Otherwise, the car becomes the leader of a new fleet, and incoming is updated to its arrival time:
for a in arrive:
if a <= incoming:
fleets -= 1
else:
incoming = a
Finally, the method returns the computed number of fleets:
return fleets
Edge Cases Handled
When the input lists position and speed are empty, len(position) evaluates to zero, and the method correctly returns zero fleets without entering the loop.
If multiple cars share the same position, the sorting step places them together, and the subsequent arrival time calculation treats each car independently. Cars that have identical arrival times are considered part of the same fleet because the condition a <= incoming will be true for the later car, causing a fleet count reduction.
Cars with a speed of zero are not possible under the problem constraints; however, the division (target - p) / s would raise a runtime error if such a speed appeared. The code assumes valid positive speeds, which aligns with the intended usage.
When a car is already at the target (p == target), its arrival time becomes zero. Since incoming starts at zero, the first car at the target will be treated as a new fleet, and any subsequent car also at the target will merge into that fleet because its arrival time (zero) satisfies a <= incoming.
The algorithm also correctly handles the scenario where all cars are moving at the same speed. In that case, each car’s arrival time is strictly decreasing with its position, so each car becomes the leader of a new fleet, resulting in a fleet count equal to the number of cars.
Performance Optimizations
The solution achieves efficiency by reducing the problem to a single pass after sorting. Pairing positions with speeds using zip and sorting them in reverse order eliminates the need for additional data structures to track car ordering.
Computing arrival times with a list comprehension creates a compact array of floating-point values, allowing the subsequent loop to operate on simple numeric comparisons without recomputing the division each iteration.
The use of a single variable incoming to represent the current fleet’s arrival time avoids maintaining a stack or list of fleet times. This constant-space approach minimizes memory overhead while still correctly merging cars into fleets based on the monotonic property of arrival times after sorting.
By decrementing the fleet counter only when a car merges, the algorithm avoids extra bookkeeping for fleet members, resulting in a straightforward arithmetic update that runs in O(1) per iteration.
Overall, the combination of sorting, a precomputed arrival list, and a single scalar state variable yields a solution that processes the input with minimal computational and memory resources.
ELI5 - Simplified Explanation
Imagine a long race track where several cars are driving toward one finish line. The computer keeps track of how many groups of cars, called fleets, reach the finish line. First, the code looks at all the cars starting at different spots and calculates how long each one takes to reach the end. It starts by looking at the car closest to the finish line and works backward to the car furthest away.
Think of this like a line of cars on a highway. If a car behind is moving faster than the car in front of it, it will eventually catch up and drive right behind it, forming one single group. The code checks these arrival times one by one. If a car takes less time or the same amount of time to get to the finish line as the car ahead of it, that means it catches up and merges into the same group. When this happens, the total number of independent groups gets smaller. If a car takes longer to get to the finish line, it becomes the new leader of a different group. By the time every car is checked, the final count identifies how many distinct groups cross the line.
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++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| bujosa | Rust | ||||||||
| charles-wangkai | Java | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| bujosa | Rust | ||||||||
| charles-wangkai | Java | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1776: Car Fleet II
- problem 2211: Count Collisions on a Road
Solved On The Same Day
- problem 888: Fair Candy Swap
- problem 917: Reverse Only Letters
- problem 799: Champagne Tower
- problem 846: Hand of Straights
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