MediumNo. 0853

Car Fleet — LeetCode 853 Python Solution

Pattern
Stack
Topics
Stack, Array, Sorting, Monotonic Stack
On a study list
NeetCode 150
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
1776Car Fleet IIHard
2454Next Greater Element IVHard
2736Maximum Sum QueriesHard
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.