Leetcode #853: Car Fleet
In this guide, we solve Leetcode #853 Car Fleet in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Array, Sorting, Monotonic Stack
Intuition
We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.
Each element is pushed and popped at most once, yielding a linear-time scan.
Approach
Maintain a stack that is either increasing or decreasing, depending on the query.
When the invariant is broken, pop and resolve answers for those indices.
Steps:
- Scan elements once.
- Pop while the monotonic condition is violated.
- Use stack indices to update answers.
Python Solution
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
The time complexity is O(n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.