n cars drive to the same target on a one-lane road. A faster car that catches a slower one ahead slows down and they become a fleet. Given each car's position and speed, return how many fleets arrive at the target.
The stack only ever needs its top. Walk from the front car back, tracking the slowest arrival time ahead; a car that would arrive later than that starts a new fleet.
1function carFleet(target: number, position: number[], speed: number[]): number {2const order = position.map((_, i) => i).sort((a, b) => position[b] - position[a]);3let fleets = 0, lead = 0;4for (const i of order) {5const time = (target - position[i]) / speed[i];6if (time > lead) { fleets++; lead = time; }7}8return fleets;9}
Sort cars front to back.
Space: play/pause · ←/→: step