LeetCode #853 Medium

Car Fleet

Car Fleet is LeetCode 853 (Medium). n cars drive along a one-lane road toward mile target. Car i starts at position[i] and drives at speed[i]. A car can never pass the car in front: when it catches up, it slows down and the two drive on together as one fleet. A car that catches a fleet exactly at the target also joins it. Return how many fleets arrive.

  • Up to 10⁵ cars, each starting at a different position before the target.
  • Every speed is at least 1, so every car arrives.
Constraints
  • n == position.length == speed.length
  • 1 <= n <= 10⁵
  • 0 < target <= 10⁶
  • 0 <= position[i] < target
  • All the values of position are unique.
  • 0 < speed[i] <= 10⁶
stacksortinggreedy
Open on LeetCode ↗
02

Intuition

Whether one car catches another depends on arrival times, not speeds. Driving alone, car i would reach the target at (target - position[i]) / speed[i].

Now walk from the car nearest the target back to the one furthest away. The nearest car has nothing in front of it, so it leads a fleet. A car behind a fleet that would arrive no later than that fleet must catch it on the way, and from then on it arrives with the fleet. A car that would arrive later never catches up, so it leads a new fleet, and its time becomes the one cars further back must beat.

So the answer is how many times the arrival time goes up as you walk back from the target.

How to spot this pattern

Objects move in one line and cannot pass each other, so each one is only affected by what is in front of it. Sort by position, handle the front first, and keep just enough about the group ahead to decide each new object.

03

Approach

Try it first

Before reading on, write the arrival time of each car for target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]. Then read the times from the car nearest the target backwards and look for a pattern. Aim for O(n log n).

1

Sort nearest the target first

Pair each position with its speed and sort by position, largest first. A car is only ever held up by cars in front of it, so in this order the cars that could block the current one have all been seen.

2

Turn each car into an arrival time

Compute (target - pos) / spd as a float. The car behind catches the one in front before or at the target exactly when its own time is no larger, so comparing two numbers replaces any meeting-point algebra.

3

Compare with the fleet ahead

Keep lead_time, the arrival time of the nearest fleet in front. If the current car's time is larger, it never catches that fleet: count a new fleet and store its time. Otherwise it joins, and lead_time stays, since the car now arrives with that fleet.

4

Why one number is enough

Each new fleet arrives later than every fleet in front of it, so lead_time is also the largest time seen so far. A car that cannot catch the nearest fleet is stuck behind it and can never reach the fleets further ahead, so nothing else needs to be stored.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def carFleet(self, target, position, speed):
▶3 cars = sorted(zip(position, speed), reverse=True)
▶4 fleets, lead_time = 0, 0.0
▶5 for pos, spd in cars:
▶6 time = (target - pos) / spd
▶7 if time > lead_time:
▶8 fleets += 1
▶9 lead_time = time
▶10 return fleets
roadtarget012108530arrival time, nearest car firstat 10, speed 2at 8, speed 4at 5, speed 1at 3, speed 3at 0, speed 1sort: nearest the target first
cars5
target12
A car is only ever held up by cars in front of it, so the cars are handled from the one nearest the target backwards. Each row will show how long that car would take to arrive on its own: distance left divided by speed.
roadtarget012108530arrival time, nearest car firstfleet ahead: 1at 10, speed 21fleet 1at 8, speed 4at 5, speed 1at 3, speed 3at 0, speed 1nearest car arrives at 1 → fleet 1
time1
fleet aheadnone
fleets1
The car at 10 has 2 to go at speed 2, so alone it arrives at 1. Nothing is in front of it, so it leads fleet 1.
roadtarget012108530arrival time, nearest car firstfleet ahead: 1at 10, speed 21fleet 1at 8, speed 41fleet 1at 5, speed 1at 3, speed 3at 0, speed 11 ties 1 → joins fleet 1
time1
fleet ahead1
fleets1
The car at 8 has 4 to go at speed 4, so alone it arrives at 1. That is exactly the fleet's time, so it catches the fleet right at the target, which still counts as joining it. It now arrives at 1 with fleet 1, and the time to beat stays 1.
roadtarget012108530arrival time, nearest car firstfleet ahead: 7at 10, speed 21fleet 1at 8, speed 41fleet 1at 5, speed 17fleet 2at 3, speed 3at 0, speed 17 is later than 1 → new fleet 2
time7
fleet ahead1
fleets2
The car at 5 has 7 to go at speed 1, so alone it arrives at 7. That is later than the fleet ahead (1), so it can never catch it and leads fleet 2. Cars further back now have to beat 7.
roadtarget012108530arrival time, nearest car firstfleet ahead: 7at 10, speed 21fleet 1at 8, speed 41fleet 1at 5, speed 17fleet 2at 3, speed 33fleet 2at 0, speed 13 is not later than 7 → joins fleet 2
time3
fleet ahead7
fleets2
The car at 3 has 9 to go at speed 3, so alone it arrives at 3. The fleet ahead arrives at 7, later than that, so this car catches it on the way and slows down. It now arrives at 7 with fleet 2, and the time to beat stays 7.
roadtarget012108530arrival time, nearest car firstfleet ahead: 12at 10, speed 21fleet 1at 8, speed 41fleet 1at 5, speed 17fleet 2at 3, speed 33fleet 2at 0, speed 112fleet 312 is later than 7 → new fleet 3
time12
fleet ahead7
fleets3
The car at 0 has 12 to go at speed 1, so alone it arrives at 12. That is later than the fleet ahead (7), so it can never catch it and leads fleet 3. Cars further back now have to beat 12.
roadtarget012108530arrival time, nearest car firstfleet ahead: 12at 10, speed 21fleet 1at 8, speed 41fleet 1at 5, speed 17fleet 2at 3, speed 33fleet 2at 0, speed 112fleet 3answer: 3 fleets
answer3
Every car is placed. The arrival time went up 3 times on the walk back from the target, once for each car that leads a fleet, so 3 fleets arrive.
05

Common pitfalls

Walking from the back of the road

✗ Wrong
cars = sorted(zip(position, speed))
✓ Right
cars = sorted(zip(position, speed), reverse=True)

From the back, the car being judged has not yet met the cars that block it, so the running time means nothing. On target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3] this returns 1 instead of 3.

Splitting cars that arrive together

✗ Wrong
if time >= lead_time:
✓ Right
if time > lead_time:

A car whose time equals the fleet's catches it exactly at the target, and that still counts as one fleet. On target = 10, position = [6, 8], speed = [2, 1] both times are 2, and >= returns 2 instead of 1.

Integer division in C++ or Java

✗ Wrong
double time = (target - pos) / spd;
✓ Right
double time = (double)(target - pos) / spd;

Both operands are int, so the division drops the fraction before the result becomes a double. On target = 10, position = [0, 1], speed = [3, 3] the times 3.33 and 3 both become 3, the cars merge, and the answer 2 turns into 1.

06

Edge cases

One car

Its time is positive because it starts before the target, so it beats the starting lead_time of 0 and the answer is 1.

A faster car that starts far back

With target = 10, a car at 0 with speed 5 arrives at 2 and a car at 9 with speed 1 arrives at 1. The fast car is still 2 behind on arrival time, so it never catches up and the answer is 2.

07

Complexity

Time
O(n log n)
Space
O(n)
Sorting the n cars dominates; the walk back from the target is one pass. The sorted pairs take O(n) space, and the walk itself keeps only two numbers.
08

Car Fleet FAQ

Do I need a stack?

No. The common stack version pushes each car's time and pops it again when that car joins the fleet in front, so the stack ends up holding one time per fleet. Only its top is ever compared, and one variable holding that top does the same job.

Are floating-point arrival times safe here?

Yes. Two cars tie only when their two fractions are equal, and equal fractions divide to the same double. Two different fractions with these limits differ by at least about one part in 10¹², while a double keeps about 16 digits. For exact integer maths, compare (target - p1) * s2 with (target - p2) * s1 in 64-bit integers instead.