Car Fleet — LeetCode 853 Python Solution

MediumStackArraySortingMonotonic Stack
Problem
#853
Pattern
Stack
Reading time
2 min

The problem

There are n cars at given miles away from the starting mile 0, traveling to reach the mile target. You are given two integer arrays position and speed, both of length n, where position[i] is the starting mile of the ith car and speed[i] is the speed of the ith car in miles per hour.

Python solution

Python
class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        idx = sorted(range(len(position)), key=lambda i: position[i])
        ans = pre = 0
        for i in idx[::-1]:
            t = (target - position[i]) / speed[i]
            if t > pre:
                ans += 1
                pre = t
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 853. Car Fleet is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 853. Car Fleet?
LeetCode 853. Car Fleet is rated Medium on LeetCode.
What is the time complexity of LeetCode 853. Car Fleet?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 853. Car Fleet?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 853. Car Fleet cover?
LeetCode 853. Car Fleet is tagged Stack, Array, Sorting and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview