15% off all plans & roadmaps Use code
See plansCar Fleet
- LeetCode 853
- Medium
- Stack Patterns
- Monotonic Stack
Updated
TL;DR: Count how many groups of cars reach the target together when no car can pass another. Sort by position, compute each arrival time, and count every car that arrives strictly later than all fleets ahead of it.
Problem
There is a road with a destination at mile target. You are given two integer arrays, position and speed, of the same length. Car i starts at position[i] and drives toward target at the constant speed speed[i].
Cars cannot pass each other. If a faster car comes up behind a slower car, it slows down to the slower car's speed and they travel together. A fleet is a group of one or more cars that arrive at target at the same time. A car that never catches anyone is a fleet on its own.
Return the number of fleets that arrive at target.
Example 1
Input: target = 20, position = [3,8,14,17], speed = [5,3,2,1] Output: 2 Explanation: The cars at 17 and 14 reach the target at the same time, so they form one fleet. The car at 8 is a second fleet, and the car at 3 catches it before the target. That gives two fleets.
Example 2
Input: target = 30, position = [4,10,18,25], speed = [6,4,3,2] Output: 3 Explanation: The car at 25 arrives after 2.5 time units and the car at 18 after 4, so they stay separate. The car at 10 would arrive after 5, and the car at 4 catches it on the way. That gives three fleets.
Example 3
Input: target = 25, position = [2,7,16,21], speed = [2,5,2,4] Output: 3 Explanation: The car at 21 is the first fleet. The car at 7 catches the car at 16 and they form the second fleet. The car at 2 is too slow to catch that fleet and stays alone.
Constraints
1 <= target <= 10^61 <= position.length == speed.length <= 10^50 <= position[i] < target1 <= speed[i] <= 10^6- All values in
positionare distinct. - Every
position[i]andspeed[i]is an integer, and both describe the same car.
Constraints that matter
- n up to 10^5 rules out comparing every car with every other car in the worst case, which is about 10^10 operations. You need roughly O(n log n).
- Positions are distinct, so after sorting there is a strict order from the car nearest the target to the farthest. No tie-breaking by speed is needed.
- All values are integers, so each arrival time is a fraction (target - position) / speed. Cross-multiplying compares two times exactly with no floating-point error.
- The products reach about 10^6 * 10^6 = 10^12, which overflows a 32-bit int. Java, C++ and C# need 64-bit integers for the comparison.
position[i] < targetmeans every car has a positive distance to travel, so every arrival time is greater than zero.
Hints
Hint 1
Cars cannot pass, so a car's real arrival time depends only on the cars ahead of it.
Hint 2
For every car, ask whether it leads its own fleet.
Solution
Intuition
Cars cannot pass, so a car's real arrival time depends only on the cars ahead of it. If you ignore blocking, car i needs (target - position[i]) / speed[i] time units. Call that its solo time. A car with a smaller solo time than a car ahead of it will catch that car, and from then on it travels at the slower pace.
Picture a single-file line of runners finishing a race, read from the front. The stack top is the finish time of the latest group, and a runner who finishes no later than that group joins it and adds nothing to the count.
That suggests looking at cars in order from the one nearest the target to the one farthest away. For each car, the only question is whether it arrives strictly later than every fleet already formed ahead of it. If yes, it never catches anyone and starts a new fleet. If its solo time is less than or equal to the fleet ahead, it merges into that fleet.
This is a sort plus a monotonic stack. After sorting by position, you keep a stack of fleet arrival times. A new time is pushed only when it is strictly larger than the top, so the stack is strictly increasing from bottom to top. Nothing is ever popped, because a merged car adds no entry. The final stack size is the answer.
Comparing with the top is enough because the top is the largest time so far. A car slower than the top fleet cannot be caught by that fleet's cars, and no fleet further ahead arrives later than the top. A car faster than the top fleet merges into it and takes the top's time.
Try Example 1 with target 20. Sorted from the front, the cars at 17, 14, 8, 3 have solo times 3, 3, 4 and 3.4. The stack gets 3, skips 3 (equal means same fleet), pushes 4, and skips 3.4 because it is below 4. The stack holds two entries, so the answer is 2.
Worked example
Input: target = 1, position = [0], speed = [1] Output: 1 Explanation: There is one car, so there is one fleet. It needs (1 - 0) / 1 = 1 time unit to arrive, and no car sits ahead of it that could block it.
Approach 1: Brute force
For every car, ask whether it leads its own fleet. A car leads a fleet when no car ahead of it has a solo time greater than or equal to its own. If such a car exists, this car is caught by that car's fleet or reaches the target with it, so it adds no new fleet.
Scan every other car, keep only those with a larger position, and compare solo times. Count the cars for which no such blocker exists. Each fleet is counted exactly once, by its frontmost car. Compare times as fractions with cross-multiplication so the answer is exact.
Steps
- Set
fleets = 0. - For each car
i, compute its distanced_i = target - position[i]. - Loop over every car
jand skip it unlessposition[j] > position[i]. - For each car
jahead, computed_j = target - position[j]and checkd_j * speed[i] >= d_i * speed[j]. This says time_j >= time_i without division. - If any such
jexists, cariis absorbed. Stop checking and move to the next car. - If no
jblocks cari, incrementfleets. - Return
fleets.
Dry run
Example: target = 1, position = [0], speed = [1].
- Car 0 has distance 1 - 0 = 1.
- The inner loop looks at car 0 itself, but
position[0] > position[0]is false, so nothing is compared. - No car ahead blocks it, so
fleetsbecomes 1.
The result is 1, which matches the expected output.
A larger check uses target 20, position [3,8,14,17], speed [5,3,2,1]. The solo times are 3.4, 4, 3, 3 for the cars at 3, 8, 14, 17. The car at 17 has no car ahead, so it counts. The car at 14 sees 17 with time 3 >= 3, so it is absorbed.
The car at 8 sees times 3 and 3, both below 4, so it counts. The car at 3 sees the car at 8 with time 4 >= 3.4, so it is absorbed. The total is 2.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the number of cars. The outer loop runs n times and the inner loop can scan up to n other cars, so the worst case is about n * n comparisons. That happens when no car is ever blocked, which makes the early break useless, and at n = 10^5 it means about 10^10 comparisons, which is too slow. Only a few integers are stored, so extra space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
n = len(position)
fleets = 0
for i in range(n):
di = target - position[i]
blocked = False
for j in range(n):
if position[j] > position[i]:
dj = target - position[j]
# time_j >= time_i <=> dj / speed[j] >= di / speed[i]
if dj * speed[i] >= di * speed[j]:
blocked = True
break
if not blocked:
fleets += 1
return fleets
JavaTested in our runner
import java.util.*;
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
int fleets = 0;
for (int i = 0; i < n; i++) {
long di = target - position[i];
boolean blocked = false;
for (int j = 0; j < n; j++) {
if (position[j] > position[i]) {
long dj = target - position[j];
// time_j >= time_i without division
if (dj * speed[i] >= di * speed[j]) {
blocked = true;
break;
}
}
}
if (!blocked) fleets++;
}
return fleets;
}
}
C++Tested in our runner
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = position.size();
int fleets = 0;
for (int i = 0; i < n; i++) {
long long di = target - position[i];
bool blocked = false;
for (int j = 0; j < n; j++) {
if (position[j] > position[i]) {
long long dj = target - position[j];
// time_j >= time_i without division
if (dj * speed[i] >= di * speed[j]) {
blocked = true;
break;
}
}
}
if (!blocked) fleets++;
}
return fleets;
}
};
JavaScriptTested in our runner
/**
* @param {number} target
* @param {number[]} position
* @param {number[]} speed
* @return {number}
*/
var carFleet = function(target, position, speed) {
const n = position.length;
let fleets = 0;
for (let i = 0; i < n; i++) {
const di = target - position[i];
let blocked = false;
for (let j = 0; j < n; j++) {
if (position[j] > position[i]) {
const dj = target - position[j];
// products stay below 10^12, which is exact in a double
if (dj * speed[i] >= di * speed[j]) {
blocked = true;
break;
}
}
}
if (!blocked) fleets++;
}
return fleets;
};
GoTested in our runner
func carFleet(target int, position []int, speed []int) int {
n := len(position)
fleets := 0
for i := 0; i < n; i++ {
di := target - position[i]
blocked := false
for j := 0; j < n; j++ {
if position[j] > position[i] {
dj := target - position[j]
// time_j >= time_i without division
if dj*speed[i] >= di*speed[j] {
blocked = true
break
}
}
}
if !blocked {
fleets++
}
}
return fleets
}
C#Tested in our runner
public class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.Length;
int fleets = 0;
for (int i = 0; i < n; i++) {
long di = target - position[i];
bool blocked = false;
for (int j = 0; j < n; j++) {
if (position[j] > position[i]) {
long dj = target - position[j];
// time_j >= time_i without division
if (dj * speed[i] >= di * speed[j]) {
blocked = true;
break;
}
}
}
if (!blocked) fleets++;
}
return fleets;
}
}

Solution pattern
Monotonic Stack
Part of Stack Patterns
Approach 2: Sort, then monotonic stack of arrival timesOptimalMonotonic Stack
What's slow: the brute force re-checks every car ahead for every car, even though most of that information is redundant. If you already know the fleets ahead, the only thing that matters is the latest arrival time among them.
The insight that fixes it: sort the cars by position, nearest to the target first, and keep a stack of fleet arrival times. For each car compute its solo time. If it is strictly greater than the top of the stack, no fleet ahead can absorb it, so push it as a new fleet. Otherwise it catches the top fleet and you push nothing.
The stack is strictly increasing, so the top is always the maximum and one comparison per car is enough. The answer is the stack size.
To avoid floating-point error, store each time as a numerator and denominator, (target - position, speed). Compare a/b > c/d as a * d > c * b. Both sides stay under 10^12 and fit in a 64-bit integer.
Steps
- Pair each position with its speed.
- Sort the pairs by position in descending order, so the car nearest the target comes first.
- Create an empty stack of (numerator, denominator) pairs, where numerator is
target - positionand denominator isspeed. - For each car, compute
num = target - positionandden = speed. - If the stack is empty, or
num * topDen > topNum * den, push(num, den). - Otherwise the car merges into the fleet at the top, so push nothing.
- Return the stack size.
Dry run
Page example: target = 1, position = [0], speed = [1].
| Step | Car (pos, speed) | Solo time | Compare with top | Action | Stack size |
|---|---|---|---|---|---|
| 1 | (0, 1) | 1/1 | stack empty | push (1, 1) | 1 |
The stack holds one entry, so the answer is 1.
A longer trace on target = 20, position = [3,8,14,17], speed = [5,3,2,1]. After sorting by position descending the cars are (17,1), (14,2), (8,3), (3,5).
| Step | Car | Solo time | Top time | Action | Stack (times) |
|---|---|---|---|---|---|
| 1 | (17, 1) | 3/1 = 3 | none | push | [3] |
| 2 | (14, 2) | 6/2 = 3 | 3 | 3 > 3 is false, merge | [3] |
| 3 | (8, 3) | 12/3 = 4 | 3 | 4 > 3, push | [3, 4] |
| 4 | (3, 5) | 17/5 = 3.4 | 4 | 3.4 > 4 is false, merge | [3, 4] |
The final stack size is 2, which matches Example 1.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the number of cars. Sorting costs O(n log n). The scan visits each car once with one constant-time comparison and at most one push, so it is O(n), and the sort dominates at O(n log n) overall. The sorted pair list holds n entries and the stack holds at most n entries, so extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
# nearest to the target first
cars = sorted(zip(position, speed), reverse=True)
stack = [] # (numerator, denominator) of each fleet's arrival time
for pos, sp in cars:
num = target - pos
# new fleet only if strictly later than the fleet ahead
if not stack or num * stack[-1][1] > stack[-1][0] * sp:
stack.append((num, sp))
return len(stack)
JavaTested in our runner
import java.util.*;
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
int[][] cars = new int[n][2];
for (int i = 0; i < n; i++) {
cars[i][0] = position[i];
cars[i][1] = speed[i];
}
// nearest to the target first
Arrays.sort(cars, (a, b) -> Integer.compare(b[0], a[0]));
long[] numStack = new long[n];
long[] denStack = new long[n];
int size = 0;
for (int[] car : cars) {
long num = target - car[0];
long den = car[1];
// strictly later than the fleet ahead means a new fleet
if (size == 0 || num * denStack[size - 1] > numStack[size - 1] * den) {
numStack[size] = num;
denStack[size] = den;
size++;
}
}
return size;
}
}
C++Tested in our runner
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = position.size();
vector<pair<int, int>> cars(n);
for (int i = 0; i < n; i++) {
cars[i] = {position[i], speed[i]};
}
// nearest to the target first (positions are distinct)
sort(cars.begin(), cars.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.first > b.first;
});
vector<pair<long long, long long>> st;
for (const auto& car : cars) {
long long num = target - car.first;
long long den = car.second;
// strictly later than the fleet ahead means a new fleet
if (st.empty() || num * st.back().second > st.back().first * den) {
st.push_back({num, den});
}
}
return (int)st.size();
}
};
JavaScriptTested in our runner
/**
* @param {number} target
* @param {number[]} position
* @param {number[]} speed
* @return {number}
*/
var carFleet = function(target, position, speed) {
// nearest to the target first
const cars = position.map((p, i) => [p, speed[i]]);
cars.sort((a, b) => b[0] - a[0]);
const stack = []; // [numerator, denominator] per fleet
for (const [pos, sp] of cars) {
const num = target - pos;
const top = stack[stack.length - 1];
// products stay below 10^12, which is exact in a double
if (stack.length === 0 || num * top[1] > top[0] * sp) {
stack.push([num, sp]);
}
}
return stack.length;
};
GoTested in our runner
import "sort"
func carFleet(target int, position []int, speed []int) int {
n := len(position)
cars := make([][2]int, n)
for i := 0; i < n; i++ {
cars[i] = [2]int{position[i], speed[i]}
}
// nearest to the target first
sort.Slice(cars, func(a, b int) bool {
return cars[a][0] > cars[b][0]
})
stack := make([][2]int, 0, n)
for _, car := range cars {
num := target - car[0]
den := car[1]
// strictly later than the fleet ahead means a new fleet
if len(stack) == 0 {
stack = append(stack, [2]int{num, den})
continue
}
top := stack[len(stack)-1]
if num*top[1] > top[0]*den {
stack = append(stack, [2]int{num, den})
}
}
return len(stack)
}
C#Tested in our runner
public class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.Length;
// nearest to the target first
int[] order = Enumerable.Range(0, n).OrderByDescending(i => position[i]).ToArray();
long[] numStack = new long[n];
long[] denStack = new long[n];
int size = 0;
foreach (int i in order) {
long num = target - position[i];
long den = speed[i];
// strictly later than the fleet ahead means a new fleet
if (size == 0 || num * denStack[size - 1] > numStack[size - 1] * den) {
numStack[size] = num;
denStack[size] = den;
size++;
}
}
return size;
}
}
Common mistakes
- Sorting by position ascending. If you scan from the rear, the fleet ahead is not known yet and the comparison with the top is meaningless. Sort descending so the car nearest
targetgoes first. - Using
time >= topto push a new fleet, or<to merge. Equal arrival times mean the cars arrive together, which is one fleet. Push only on a strictly greater time and merge on<=. - Computing
(target - position) / speedwith integer division, as in(target - pos) // spor/on ints in Java and C++. Times like 2.5 and 2 become equal and fleets merge wrongly. Use cross-multiplication or a floating-point division. - Multiplying two ints in Java, C++ or C# without widening, as in
num * denwithinttypes. The product can reach 10^12 and overflow. Declare the numerator and denominator aslongorlong longbefore multiplying. - Sorting only the
positionarray and leavingspeeduntouched. The two arrays describe the same cars, so the pairs must move together. Sort pairs or sort indices. - Comparing each car with every earlier fleet instead of only the top of the stack. It still works but brings back O(n^2) work. The stack is increasing, so the top is the maximum and one comparison is enough.
Edge cases
- One car, such as
target = 1, position = [0], speed = [1]: the answer is 1. - All cars at distinct positions but with the same solo time, for instance times all equal to 5: they form one fleet, so the answer is 1.
- Speeds so that the rear car is much faster than everyone ahead: every car merges into the front fleet and the answer is 1.
- Speeds so that cars farther back are always slower and arrive later: no one catches anyone, so the answer equals n.
- Input positions given in unsorted order, like
[17, 3, 14, 8]: the sort must carry each speed with its position. - Maximum values
target = 10^6,position = 0,speed = 1alongsidespeed = 10^6: cross-multiplied products reach 10^12, so 32-bit arithmetic overflows.
Follow-ups interviewers ask
- Can you avoid floating point entirely?
- Yes. Store each arrival time as the pair (target - position, speed) and compare a/b > c/d as a * d > c * b. The products are at most 10^6 * 10^6 = 10^12, which fits in a 64-bit integer and in a JavaScript double. That makes every comparison exact.
- Do you actually need a stack, or does a single variable do?
- A single variable is enough. Only the top of the stack is ever read, and nothing is ever popped, so keep the latest fleet's arrival time and a counter. When a car's time is strictly greater than that variable, increment the counter and replace the variable. The sort still costs O(n log n) and O(n) space.
- Can you beat O(n log n)?
- Positions are integers below target, so you can bucket-sort by position when target is small. Allocate an array of size target, place each car at its position, and scan from target - 1 down to 0. That costs O(n + target) time and O(target) space. With target up to 10^6 and n up to 10^5 this helps only in some cases, so the comparison sort is the general answer.
Car Fleet FAQ
What is the time complexity of Car Fleet?
O(n log n), where n is the number of cars. Sorting by position costs O(n log n) and the single pass over the sorted cars is O(n). Space is O(n) for the sorted pairs and the stack.
Why use a monotonic stack for Car Fleet?
After sorting from the target backward, the fleet arrival times you keep are strictly increasing, which is the monotonic stack invariant. Each new car only needs to be compared with the top, the latest fleet. If it is strictly later, it is pushed as a new fleet. Otherwise it merges and nothing changes.
Why does the car fleet solution sort by position descending?
A car's final time depends only on the cars ahead of it. Processing from the one nearest the target means every fleet in front has been decided before the next car is considered. Scanning the other way would require knowing fleets you have not built yet.
Should Car Fleet use floating-point division or integer cross-multiplication?
Either works within these limits, but integer cross-multiplication is exact and avoids rounding questions when two times are equal. Never use integer division: (target - pos) // speed truncates 2.5 to 2 and breaks the comparison. If you use floats, divide with a floating type, such as / in Python or a cast to double in Java and C++.
Can Car Fleet be solved in O(1) extra space?
Not in the usual sense. You can replace the stack with one variable and a counter, but you still need the cars in sorted order. Sorting the pairs needs O(n) extra space, or you can sort in place in languages that allow it and pay for the pairing. A bucket by position uses O(target) space instead.
How is Car Fleet (LeetCode 853) different from a simulation?
A simulation moves every car in small time steps and merges them when they meet. That introduces time-step choices and rounding problems. The accepted solution never simulates motion. It computes each car's solo arrival time and uses the fact that cars cannot pass to decide merges by comparison alone.
Asked at
See which companies ask this — Pro
Related problems
- Daily Temperatures · same technique: Monotonic Stack
- Online Stock Span · same technique: Monotonic Stack
- Next Greater Element II · same technique: Monotonic Stack
- Remove K Digits · same technique: Monotonic Stack
- Sum of Subarray Minimums · same technique: Monotonic Stack
- Largest Rectangle in Histogram · next harder, same pattern
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Valid Parenthesis String · same pattern: Stack Patterns
- Simplify Path · same pattern: Stack Patterns