Algo-Sim › Stacks & Monotonic Stack
Car Fleet
Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Count the groups of cars that reach the target together: sort by position and stack the arrival times.
Problem
Cars drive along a one-lane road toward target; car i starts at position[i] with speed speed[i]. A car can never pass the one ahead: when it catches up it slows down and the two travel together as a fleet. Cars that meet exactly at target also count as one fleet. Return the number of fleets that arrive.
Constraints
- 1 ≤ n ≤ 10⁵
- 0 < target ≤ 10⁶
- 0 ≤ position[i] < target, all distinct
- 0 < speed[i] ≤ 10⁶
Edge cases to test
- One car
- Cars arriving at exactly the same time merge
- A car already at the target
Follow-up questions
- Why sort by position, closest first?
- A car can only be slowed by the cars in front of it; scanning from the front lets each car compare with the fleet ahead.
- Can you avoid floating point?
- Compare arrival times by cross-multiplying
(target − p₁)·s₂with(target − p₂)·s₁in 64 bits.
Solution
Java
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> position[b] - position[a]);
Deque<Double> stack = new ArrayDeque<>();
for (int i : order) {
double time = (double) (target - position[i]) / speed[i];
if (stack.isEmpty() || time > stack.peek()) {
stack.push(time);
}
}
return stack.size();
}Python
def car_fleet(target, position, speed):
cars = sorted(zip(position, speed), reverse=True)
stack = []
for p, s in cars:
time = (target - p) / s
if not stack or time > stack[-1]:
stack.append(time)
return len(stack)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int carFleet(int target, vector<int> &position, vector<int> &speed) {
int n = int(position.size());
vector<int> order = vector<int>(n);
for (int i = 0; i < n; i++)
order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) { return position[a] > position[b]; });
deque<double> stack = {};
for (int i : order) {
double time = (double)(target - position[i]) / speed[i];
if (stack.empty() || time > stack.back()) {
stack.push_back(time);
}
}
return int(stack.size());
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)