Car Fleet (LeetCode 853): Solution and Explanation
Cars drive toward the same target on a single lane where passing is impossible. A faster car that catches a slower one slows down and travels with it as a fleet. Count how many separate fleets arrive at the target.
Watch it run step by step
Try your own input and write the code →Intuition
Simulating the road minute by minute would work in principle, but positions and speeds can be large, and handling the merges correctly is messy. The cleaner idea is to stop thinking about where cars are and think about when each car would reach the target if it drove alone. That time is (target - position) / speed.
Now consider the cars in order from closest to the target to farthest. The car in front sets a pace. A car behind it catches up before the target exactly when its solo arrival time is less than or equal to the front car's arrival time. If it catches up, it joins that fleet, and from then on it arrives when the fleet arrives, so its own faster time no longer matters.
If a car behind would arrive strictly later than the fleet ahead, it never catches up, and it becomes the leader of a new fleet. Any car further back now has to be compared against this slower new leader, because it would reach this fleet first.
So the algorithm is: sort by position from nearest to the target to farthest, compute arrival times, and keep a stack of fleet arrival times. Push each car's time; if it is not greater than the time under it, the car merges and you pop it. The stack size at the end is the number of fleets. The stack only ever needs its top, so a single variable would also work.
Approach: Sort by position and stack arrival times
- Pair each car's position with its speed.
- Sort the pairs by position and iterate in reverse, from the car closest to the target to the farthest.
- Push the car's solo arrival time
(target - p) / sontostack. - If the stack has at least two entries and the new time is less than or equal to the one below it, the car catches the fleet ahead, so pop it.
- Return
len(stack), the number of distinct fleets.
Step-by-step example
target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
- Sorted from nearest to farthest: (10,2), (8,4), (5,1), (3,3), (0,1).
- Car at 10 needs (12 - 10) / 2 = 1 hour. Push 1. Car at 8 needs 4 / 4 = 1 hour, which is not more than 1, so it joins that fleet and is popped. Stack: [1].
- Car at 5 needs 7 / 1 = 7 hours, slower than 1, so it starts a new fleet. Stack: [1, 7].
- Car at 3 needs 9 / 3 = 3 hours, which is at most 7, so it catches the car at 5 and is popped. Stack: [1, 7].
- Car at 0 needs 12 / 1 = 12 hours, slower than 7, so it forms a third fleet. Stack: [1, 7, 12], and the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
3 pair = [[p, s] for p, s in zip(position, speed)]
4
5 stack = []
6 for p, s in sorted(pair)[::-1]: # Reverse sorted order
7 stack.append((target - p) / s)
8 if len(stack) >= 2 and stack[-1] <= stack[-2]:
9 stack.pop()
10 return len(stack)1class Solution {
2 public int carFleet(int target, int[] position, int[] speed) {
3 int n = position.length;
4 double[][] pair = new double[n][2];
5 for (int i = 0; i < n; i++) {
6 pair[i][0] = position[i];
7 pair[i][1] = speed[i];
8 }
9 Arrays.sort(pair, (a, b) -> Double.compare(b[0], a[0]));
10
11 Stack<Double> stack = new Stack<>();
12 for (int i = 0; i < n; i++) {
13 stack.push((target - pair[i][0]) / pair[i][1]);
14 if (stack.size() >= 2 && stack.peek() <= stack.get(stack.size() - 2)) {
15 stack.pop();
16 }
17 }
18 return stack.size();
19 }
20}1class Solution {
2public:
3 int carFleet(int target, vector<int>& position, vector<int>& speed) {
4 vector<pair<int, int>> pair;
5 for (int i = 0; i < position.size(); i++) {
6 pair.push_back({position[i], speed[i]});
7 }
8 sort(pair.rbegin(), pair.rend());
9
10 vector<double> stack;
11 for (auto p : pair) {
12 stack.push_back((double)(target - p.first) / p.second);
13 if (stack.size() >= 2 && stack.back() <= stack[stack.size() - 2]) {
14 stack.pop_back();
15 }
16 }
17 return stack.size();
18 }
19};Time and space complexity
O(n log n)
Sorting the cars by position dominates. The pass over the sorted cars is linear, with at most one push and one pop per car.
O(n)
The list of pairs, the sorted copy and the stack can each hold up to n entries.
Other approaches
Single variable for the leading fleet (time O(n log n), space O(n))
Since only the top of the stack is ever compared, keep one variable for the slowest arrival time seen so far and count a new fleet whenever a car's time exceeds it. It uses less memory and is equally clear.
Counting sort by position (time O(n + target), space O(target))
Positions are integers below the target, so you can place each car's arrival time in an array indexed by position and sweep it from the target downward. This removes the sort when the target is small enough to allocate.
Common mistakes
- Processing cars from farthest to nearest. The fleet structure is determined by the cars ahead, so you must start at the front.
- Using a strict
<when comparing times. A car that arrives at exactly the same moment catches up at the target and counts as the same fleet. - Using integer division for arrival times in Java or C++, which rounds and makes different times look equal.
- Comparing a new car against the car directly ahead instead of the fleet ahead. Once cars merge, the fleet's time is the slower leader's time.
Frequently asked questions
Why do we sort cars by position in Car Fleet?
A car can only be blocked by cars in front of it. Processing from the front means that when you look at a car, the fleets ahead of it are already decided.
Why compare arrival times instead of speeds?
A faster car that starts far back may still arrive later than a slow car near the target. The solo arrival time combines distance and speed into the one number that decides whether one car catches another before the target.
What is the time complexity of Car Fleet?
It is O(n log n) because of the sort. The stack pass afterwards is O(n).
Is the stack really necessary?
No. Only the most recent fleet's arrival time matters, so one variable is enough. The stack version just makes the fleet structure easy to visualize.