Car Fleet II

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 i^th car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
  • speedi is the initial speed of the i^th 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 i^th 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.

Example 1
Inputcars = [[1,2],[2,1],[4,3],[7,2]]
Output[1,-1,3,-1]
After exactly one second, the first car collides with the second car, and after exactly three seconds, the third car collides with the fourth car.
Example 2
Inputcars = [[3,4],[5,4],[6,3],[9,1]]
Output[2,1,1.5,-1]
The first, second, and third cars collide with their next cars after 2, 1, and 1.5 seconds respectively, while the last car never collides with a next car.

Constraints

  • 1 <= cars.length <= 10^5
  • 1 <= positioni, speedi <= 10^6
  • positioni < positioni+1

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate