1. Arrival time
Time to reach the target is distance over speed.
(target - pos) / speed[i]Typorithm · medium
Step 1 of 8 · intro card
Monotonic Stack
Sort cars from closest to target; a car arriving later than the fleet ahead starts a new fleet, counted by the stack.
Each car's arrival time is the remaining distance divided by its speed.
Processing cars from closest to the target, a car that would arrive after the one ahead can never catch it, so it forms a new fleet.
A car that would arrive sooner is blocked and merges into the fleet ahead.
Arrival time = (target - pos) / speed.
Sort by position descending.
Later arrival than the lead = new fleet.
function carFleet(target, position, speed) {
const cars = position
.map((pos, i) => [pos, (target - pos) / speed[i]])
.sort((a, b) => b[0] - a[0]);
const stack = [];
for (const [, time] of cars) {
if (stack.length === 0 || time > stack[stack.length - 1]) {
stack.push(time);
}
}
return stack.length;
}Connect each part of the code to the concept before you type.
Time to reach the target is distance over speed.
(target - pos) / speed[i]Sort by position descending so the lead car comes first.
.sort((a, b) => b[0] - a[0])A slower (later-arriving) car starts a new fleet ahead.
if (stack.length === 0 || time > stack[stack.length - 1]) {The stack size is the number of distinct fleets.
return stack.lengthRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.