HardNo. 1776
Car Fleet II — LeetCode 1776 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Stack, Array, Math, Monotonic Stack, Heap (Priority Queue)
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
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 ansComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1776. Car Fleet II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0853 | Car Fleet | Medium |
| 0973 | K Closest Points to Origin | Medium |
| 1878 | Get Biggest Three Rhombus Sums in a Grid | Medium |
| 2344 | Minimum Deletions to Make Array Divisible | Hard |
| 0215 | Kth Largest Element in an Array | Medium |
| 0218 | The Skyline Problem | Hard |
Frequently asked questions
- How hard is LeetCode 1776. Car Fleet II?
LeetCode 1776. Car Fleet II is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1776. Car Fleet II?
The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 1776. Car Fleet II?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1776. Car Fleet II cover?
LeetCode 1776. Car Fleet II is tagged Stack, Array, Math, Monotonic Stack and Heap (Priority Queue) on LeetCode.