Visualize

Pattern visualizer

Car Fleet

Positions and speeds are a distraction; convert every car to the single number that decides everything — how long it would take to reach the target alone. Sort the cars so the one nearest the target comes first, because that car has nothing in front of it and its arrival time is final. Then walk backwards through traffic: a car whose solo time is at most the time of the fleet already ahead must run into it, so it is absorbed and changes nothing. Only a car SLOWER than everything ahead survives as its own fleet, and it becomes the new obstacle for everyone behind. The surviving times form a strictly increasing stack, and its height is the answer. Animated on: target = 12, position = [3, 10, 0, 8, 5, 4], speed = [3, 2, 1, 4, 1, 2] — cars cannot pass, so a faster car that catches a slower one joins its fleet. How many fleets reach the target?.

Sort nearest-to-target first, keep a monotonic stack of arrival times

time O(n log n)space O(n)step 1 / 10
p3 s3
[0]
p10 s2
[1]
p0 s1
[2]
p8 s4
[3]
p5 s1
[4]
p4 s2
[5]
line 1

target = 12, 6 cars given in arbitrary order. A car can never overtake, so the only thing that can slow a car down is a car AHEAD of it — which means the input order is useless and position order is everything.

Pseudocode
1FUNCTION carFleet(target, position, speed)
2 cars <- PAIRS(position, speed) SORTED BY position DESCENDING
3 stack <- EMPTY
4 FOR i <- 0 TO LENGTH(cars) - 1
5 t <- (target - cars[i].pos) / cars[i].speed
6 IF stack IS EMPTY OR t > TOP(stack) THEN
7 APPEND t TO stack
8 RETURN LENGTH(stack)

← / → step · space play · Home restart

Where to practice Stack