Python 1776.py
class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
size = len(cars)
result = [ +inf ] * size
fleets = []
for i in reversed(range(size)):
pos, speed = cars[i]
crash = +inf
while fleets:
last = fleets[-1]
lastpos, lastspeed = cars[last]
# no crash
if speed <= lastspeed:
fleets.pop()
continue
# crash, but later than an already known crash
crash = (lastpos - pos) / (speed - lastspeed)
if crash >= result[last]:
fleets.pop()
continue
# crash found !
result[i] = crash
break
fleets.append(i)
return [ -1 if r == +inf else r for r in result ]
Difficulty
and has an acceptance rate of about 58% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Heap (Priority Queue)
- Math
- Monotonic Stack
- 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 getCollisionTimes that computes, for each car in a line, the time at which it will collide with the car directly ahead of it, assuming all cars move forward on a one-dimensional road. The algorithm processes the cars from right to left, maintaining a stack-like structure (fleets) that represents candidate cars that could be collided with. The result array is filled with either the collision time or -1 when no collision occurs.
Core Logic
Initialization
size = len(cars)
result = [ +inf ] * size
fleets = []
The method first determines the number of cars, creates a result list pre-filled with positive infinity to denote “no collision”, and prepares an empty list that will act as a stack of indices of cars that are still potential collision targets.
Reverse Traversal
for i in reversed(range(size)):
pos, speed = cars[i]
Iterating from the last car toward the first ensures that when a car is examined, all cars ahead of it have already been processed and their eventual collision times are known. This direction is essential for the stack-based pruning that follows.
Stack Processing
crash = +inf
while fleets:
last = fleets[-1]
lastpos, lastspeed = cars[last]
# no crash
if speed <= lastspeed:
fleets.pop()
continue
# crash, but later than an already known crash
crash = (lastpos - pos) / (speed - lastspeed)
if crash >= result[last]:
fleets.pop()
continue
# crash found !
result[i] = crash
break
Inside the loop, the algorithm examines the car at the top of the stack (last).
-
If the current car’s speed is not greater than the speed of
last, a collision is impossible; the top of the stack is removed because it cannot serve as a collision target for any earlier car. -
When the current car is faster, a potential collision time is computed as the distance between the two cars divided by their relative speed.
-
If this computed time is not earlier than the time at which
lastitself collides with another car (result[last]), the collision would occur afterlasthas already merged into a fleet, making it irrelevant. Consequently,lastis discarded from the stack. -
If the computed time is earlier, it represents the first collision for the current car. The result entry is set, and the loop terminates.
Updating the Stack
fleets.append(i)
After processing, the current car’s index is pushed onto the stack, becoming a candidate for cars further to the left.
Final Conversion
return [ -1 if r == +inf else r for r in result ]
The sentinel +inf values are replaced with -1 to match the expected output format, indicating that those cars never collide.
Edge Cases Handled
When the input list is empty, size becomes zero, the loop body never executes, and the method returns an empty list, which correctly reflects the absence of cars.
If there is only a single car, the stack remains empty throughout the iteration, leaving its result entry as +inf. The final conversion changes this to -1, indicating no possible collision.
Cars with identical speeds are caught by the speed <= lastspeed condition; they are never considered colliding, and the corresponding stack entries are removed, preventing unnecessary calculations.
When a faster car would catch up to a slower car that itself is slated to collide later, the comparison crash >= result[last] ensures that the earlier car does not incorrectly report a collision that would be preempted by the slower car’s own collision.
The use of +inf as a sentinel avoids special-casing for “no collision” during the arithmetic and comparison steps, simplifying the logic for all scenarios.
Performance Optimizations
The algorithm achieves linear traversal by processing cars in reverse order and using a stack to store only those cars that remain viable collision targets. Each car index is pushed onto the stack exactly once and can be popped at most once, guaranteeing that the total number of stack operations scales with the number of cars.
Early elimination of impossible targets (speed <= lastspeed) prevents unnecessary division operations for cars that can never catch up.
The check crash >= result[last] discards any target that would have already merged into another fleet before the current car could reach it, reducing the depth of the stack and avoiding redundant future comparisons.
By storing the original positions and speeds in the input list and referencing them directly via indices, the code avoids copying data structures, keeping memory usage minimal.
The final list comprehension that translates +inf to -1 runs in a single pass, completing the transformation without additional loops.
ELI5 - Simplified Explanation
Imagine a long, straight road with cars driving in a line. Some cars go fast and some go slow. When a fast car is behind a slow car, it will eventually bump into the back of it. This code is like a smart teacher watching these cars to figure out exactly when those bumps will happen.
The process starts at the very back of the line and works toward the front. It keeps track of the cars that might be involved in a bump. When looking at a new car, the code checks if it is going faster than the car in front of it. If the car in front is actually faster or going the same speed, there is no way for a bump to happen, so that front car is ignored.
If the car in front is slower, there is a chance for a bump. The code calculates how long it takes to reach that car. Sometimes, a car might bump into another one that has already bumped into something else even earlier, and the code makes sure to keep track of the earliest possible time for each bump. If it turns out that a car would bump into another car way too late, it skips that one and looks for the next scenario. After figuring out the right time for a bump, the result is saved for that car. This keeps happening until all the cars have been checked.
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++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Go | Python | ||||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 853: Car Fleet
- problem 2211: Count Collisions on a Road
Solved On The Same Day
- problem 927: Three Equal Parts
- problem 2801: Count Stepping Numbers in Range
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