#1776
Car Fleet II
HardArrayMathStackHeap (Priority Queue)Monotonic StackStackGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use a stack to keep track of the cars that are still in play, allowing us to efficiently determine when collisions will occur. This reduces the number of checks we need to perform.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a stack to keep track of the collision times.
- 2Step 2: Iterate through the cars from right to left.
- 3Step 3: For each car, calculate the time to collide with the next car in the stack if it's slower.
- 4Step 4: If the current car is faster, it will not collide, so we skip it.
solution.py12 lines
1def getCollisionTimes(cars):
2 n = len(cars)
3 answer = [-1] * n
4 stack = []
5 for i in range(n - 1, -1, -1):
6 while stack and cars[i][1] > cars[stack[-1]][1]:
7 stack.pop()
8 if stack:
9 time = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])
10 answer[i] = time
11 stack.append(i)
12 return answerℹ
Complexity note: This complexity is achieved because we only iterate through the cars once and use a stack to keep track of potential collisions, leading to linear time complexity.
- 1Cars with higher speeds cannot collide with cars ahead of them.
- 2Using a stack allows us to efficiently track potential collisions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.