AlgoInsight

DSA problem

Car Fleet

MediumStacksPattern: Stackstop600GoogleAmazonUberMicrosoft

There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer arrays position and speed, both of length n, where position[i] is the position of the i-th car and speed[i] is the speed of the i-th car (in miles per hour).

A car can never pass another car ahead of it, but it can catch up to it and then drive bumper-to-bumper at the same speed. The pair of cars then becomes a single car fleet that travels at the slower car's pace. Note that a single car is also considered a car fleet, and a car that catches up exactly at the target is still considered the same fleet.

Return the number of car fleets that will arrive at the destination. The key insight is that a slower car ahead caps the speed of any faster car behind it: time-to-target only matters in non-decreasing order from the closest-to-target car backward.

The optimal approach sorts cars by position in descending order (closest to the target first) and computes each car's time-to-target as (target - position) / speed. We then walk left to right and push each time onto a stack only if it is strictly greater than the current top — meaning this car cannot catch up to the fleet ahead before reaching the target, so it starts its own fleet. Otherwise it will catch up and merge into the existing fleet, so we don't push. The final stack size is the fleet count. Sorting is O(n log n) and the walk is O(n), so the total is O(n log n).

Examples

Example 1
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation: Times to target: car@10→1.0, car@8→1.0, car@5→7.0, car@3→3.0, car@0→12.0. Sorted by position desc: (10,1.0),(8,1.0),(5,7.0),(3,3.0),(0,12.0). Push 1.0; 1.0 is not >1.0 so merge; push 7.0; 3.0 ≤ 7.0 merge; push 12.0. Stack size 3.
Example 2
Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation: A single car is a single fleet.
Example 3
Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation: Times: 25, 49, 96. Sorted by position desc: 96, 49, 25. Push 96; 49 ≤ 96 merge; 25 ≤ 96 merge. One fleet.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackarraysortingmonotonic-stack

Browse all DSA problems