Car Fleet II - Problem
Imagine a futuristic highway where self-driving cars travel in perfect formation! You have n cars on a single-lane road, each with different starting positions and speeds. Here's the twist: when faster cars catch up to slower ones, they don't just stop - they merge into a fleet and continue together at the speed of the slowest car!
Given an array cars where cars[i] = [positioni, speedi]:
- Position: Distance from the start of the road (guaranteed that cars are sorted by position)
- Speed: Initial speed in meters per second
Goal: For each car, calculate when it will collide with the next car ahead, or return -1 if no collision occurs.
Key Rules:
- Cars can only move forward and catch up to cars ahead
- When cars collide, they form a fleet moving at the slowest car's speed
- You need to account for chain reactions of collisions!
Input & Output
example_1.py โ Basic Collision
$
Input:
cars = [[1,2],[2,1],[4,3],[7,2]]
โบ
Output:
[1.0, -1, 3.0, -1]
๐ก Note:
Car 0 (pos=1, speed=2) catches Car 1 (pos=2, speed=1) in 1 second. Car 1 won't catch anyone. Car 2 (pos=4, speed=3) catches Car 3 (pos=7, speed=2) in 3 seconds. Car 3 is the last car.
example_2.py โ Chain Reaction
$
Input:
cars = [[3,4],[5,4],[6,3],[9,1]]
โบ
Output:
[2.0, 1.0, 1.5, -1]
๐ก Note:
Car 1 catches Car 2 in 1 second, forming a fleet at speed 3. Car 0 then catches this fleet in 2 seconds. Car 2 catches Car 3 in 1.5 seconds.
example_3.py โ No Collisions
$
Input:
cars = [[1,1],[2,2],[3,3]]
โบ
Output:
[-1, -1, -1]
๐ก Note:
Each car is faster than the car behind it, so no collisions occur. Cars maintain their spacing forever.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Cars are positioned on highway, each with different speeds
2
Process Right-to-Left
Start from the rightmost car and work backwards
3
Stack Management
Maintain a stack of cars that could be collision targets
4
Collision Calculation
For each car, find the earliest valid collision time
5
Chain Reaction Handling
Account for how fleet formations affect future collisions
Key Takeaway
๐ฏ Key Insight: Cars only collide with the next 'collision boundary' ahead, not arbitrary cars. Use a monotonic stack to efficiently track these boundaries!
Time & Space Complexity
Time Complexity
O(n)
Each car is pushed and popped from stack at most once
โ Linear Growth
Space Complexity
O(n)
Stack can contain up to n cars in worst case
โก Linearithmic Space
Constraints
- 1 โค cars.length โค 105
- 1 โค positioni, speedi โค 106
- positioni < positioni+1 (cars are sorted by position)
- Important: Answers within 10-5 of actual answers are accepted
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code