Car Fleet Visualizer & Step-by-Step Algorithm Solution

Calculate the number of car fleets that will arrive at the target destination using arrival times and a monotonic stack.

Category: stack | Difficulty: Medium

Tags: Stack, Sorting, Monotonic Stack

Car Fleet

Cars (Sorted by Position Descending)
[p:10, s:2]
0
[p:8, s:4]
1
[p:5, s:1]
2
[p:3, s:3]
3
[p:0, s:1]
4
Push / Pop (Top)
(Empty Stack)
Fleet Arrival Times
100%
state
target12 miles
fleets count0
Initialization
1/22
Explanation

Combine position and speed arrays, then sort cars by position in descending order (closest to target first).

Source Code
1function carFleet(target, position, speed) {
2 const cars = position.map((pos, i) => ({ pos, spd: speed[i] }));
3 cars.sort((a, b) => b.pos - a.pos);
4 const stack = [];
5 for (const car of cars) {
6 const time = (target - car.pos) / car.spd;
7 if (!stack.length || time > stack[stack.length - 1]) {
8 stack.push(time);
9 }
10 }
11 return stack.length;
12}