mediumStackAmazonGoogle
Freeway Convoy Count
Cars drive the same freeway toward a target. A car cannot overtake; it slows down to match the one in front. How many distinct convoys arrive?
Given `target` and arrays `position`/`speed`, return the number of car fleets that will arrive at the target.
Choose approach
Input
pos=10,spd=2
pos=8,spd=4
pos=5,spd=1
pos=3,spd=3
pos=0,spd=1
top
1/7
Narrationstep 1 of 7
Sort cars by position descending (closest to target first). Walk them: each car farther out joins a fleet iff its ETA strictly exceeds the slowest ETA ahead.
Variables
target=12
cars=5
How to think about it
- ETA for one car = (target − position) / speed.
- A car cannot overtake — so if it would arrive sooner than the fleet ahead, it catches up and merges.
- Walk cars from closest-to-target backwards; track the slowest ETA seen so far.
- ETA > slowest → new fleet; else merge.
Edge cases to catch in interview
- All cars same position — one fleet.
- Fastest car at the back — may catch everyone (one fleet).
- Only one car → one fleet.
Examples
Example 1
3{"target":12,"position":[10,8,0,5,3],"speed":[2,4,1,1,3]}
Example 2
1{"target":10,"position":[3],"speed":[3]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed