Car Fleet II Problem
Description
LeetCode Problem 1776.
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] = [position_i, speed_i] represents:
position_iis the distance between thei^thcar and the beginning of the road in meters. It is guaranteed thatposition_i < position_(i+1).speed_iis the initial speed of thei^thcar 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:
Input: cars = [[1,2],[2,1],[4,3],[7,2]]
Output: [1.00000,-1.00000,3.00000,-1.00000]
Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
Example 2:
Input: cars = [[3,4],[5,4],[6,3],[9,1]]
Output: [2.00000,1.00000,1.50000,-1.00000]
Constraints:
1 <= cars.length <= 10^51 <= position_i, speed_i <= 10^6position_i < position_(i+1)
Solution
Approach: Monotonic Stack
Whether car i collides depends only on the cars to its right, so we go from right to left and keep a stack of cars that i could still run into.
Look at the car j on top of the stack:
- If
iis not faster thanj, it never catchesj. Popj: it cannot be the first car thatior any car to the left ofihits. - If
iis faster, it reachesjat timet = (pos_j - pos_i) / (speed_i - speed_j). Ifjalready collided earlier thant, it has merged into a slower fleet by then, so pop it and look at the next car. - Otherwise
tis the answer fori.
If the stack becomes empty, car i never collides and its answer is -1. Finally push i. Every car is pushed and popped at most once.
Complexity: O(n) time and O(n) space.
class Solution:
def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
stk = []
n = len(cars)
ans = [-1] * n
for i in range(n - 1, -1, -1):
while stk:
j = stk[-1]
if cars[i][1] > cars[j][1]:
t = (cars[j][0] - cars[i][0]) / (cars[i][1] - cars[j][1])
if ans[j] == -1 or t <= ans[j]:
ans[i] = t
break
stk.pop()
stk.append(i)
return ans