CodeArchon

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.

1def freeway_convoy_count(target: int, position: list[int], speed: list[int]) -> int:
2 cars = sorted(zip(position, speed), reverse=True)
3 fleets = 0
4 slowest = 0.0
5 for p, s in cars:
6 t = (target - p) / s
7 if t > slowest:
8 fleets += 1
9 slowest = t
10 return fleets
Variables
target=12
cars=5

How to think about it

  1. ETA for one car = (target − position) / speed.
  2. A car cannot overtake — so if it would arrive sooner than the fleet ahead, it catches up and merges.
  3. Walk cars from closest-to-target backwards; track the slowest ETA seen so far.
  4. 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 13
{"target":12,"position":[10,8,0,5,3],"speed":[2,4,1,1,3]}
Example 21
{"target":10,"position":[3],"speed":[3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed