853. Car Fleet
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Stack
- Time
- O(n log n)
- Space
- O(n)
Standard Solution (C++)
SummaryCars head toward a shared destination at fixed speeds; a faster car catching a slower one forms a fleet moving at the slower speed. Count how many distinct fleets reach the target.
Approach
Sort cars by starting position descending (closest to the target first) and compare arrival times.
- For each car compute the time to reach the target as (target minus position) divided by speed.
- Scan from the car nearest the destination; a car forms a new fleet only if its arrival time is strictly greater than the current fleet leader's time.
- Otherwise it catches up and merges into the existing fleet.
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = position.size();
vector<pair<int,double>> cars(n);
for (int i = 0; i < n; ++i) {
cars[i] = {position[i], (double)(target - position[i]) / speed[i]};
}
sort(cars.begin(), cars.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
int fleets = 0;
double lead = 0.0;
for (auto& [pos, time] : cars) {
if (time > lead) {
fleets++;
lead = time;
}
}
return fleets;
}
}; Time O(n log n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.