There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:

  • positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
  • speedi is the initial speed of the ith car in meters per second.

For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.

Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.

Input & Output

Example 1 — Basic Case
$ Input: cars = [[1,2],[3,1],[5,3]]
Output: [2.0,-1,-1]
💡 Note: Car 0 (pos=1, speed=2) catches Car 1 (pos=3, speed=1) at time (3-1)/(2-1) = 2.0. Car 1 cannot catch Car 2 (slower speed). Car 2 is last.
Example 2 — No Collisions
$ Input: cars = [[1,1],[2,2],[3,3]]
Output: [-1,-1,-1]
💡 Note: Each car is slower than the one ahead, so no collisions occur. All return -1.
Example 3 — Multiple Collisions
$ Input: cars = [[1,4],[2,3],[4,1]]
Output: [0.5,1.0,-1]
💡 Note: Car 0 catches Car 1 at time (2-1)/(4-3) = 1.0. Car 1 catches Car 2 at time (4-2)/(3-1) = 1.0. Car 2 is last.

Constraints

  • 1 ≤ cars.length ≤ 105
  • 1 ≤ positioni, speedi ≤ 106
  • positioni < positioni+1

Visualization

Tap to expand
Car Fleet II Problem OverviewRoad0pos=1sp=21pos=3sp=12pos=5sp=3catches at t=2no collisionCar 0 will catch Car 1 at time 2.0 secondsCars 1 and 2 will not collideOutput: [2.0, -1, -1]
Understanding the Visualization
1
Input
Cars with positions and speeds on a road
2
Process
Calculate collision times considering fleet formation
3
Output
Array of collision times or -1 for no collision
Key Takeaway
🎯 Key Insight: Process cars right-to-left with a stack to handle complex fleet collision chains
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen