← DSA
MEDIUM

Car Fleet

PracticeNeetCode ↗LeetCode ↗

n cars head to the same destination on a one-lane road, each with a starting position and speed. A car that catches up to a slower car ahead is stuck behind it, and together they travel as one "fleet" at the slower car's speed. Return the number of distinct fleets that will arrive at the destination.

Example

Input target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output 3

Key Pointers

Step-by-Step Analysis

  1. Pair each car's position with its speed, and sort the pairs by position in descending order (closest to target first).
  2. Compute each car's time-to-target as (target - pos) / speed.
  3. Walk the sorted cars, keeping a stack of fleet arrival times: if a car's time is less than or equal to the time on top of the stack, it merges into that fleet — don't push anything new.
  4. If a car's time is greater than the top of the stack, it leads a new fleet — push its time.
  5. The final stack size is the number of fleets.

Complexity

Time: O(n log n) for the sort — Space: O(n)

Code

def carFleet(target: int, position: list[int], speed: list[int]) -> int:
    cars = sorted(zip(position, speed), reverse=True)
    stack = []

    for pos, spd in cars:
        time = (target - pos) / spd
        if not stack or time > stack[-1]:
            stack.append(time)

    return len(stack)

Code Explanation

How the solution above works, piece by piece.

  1. sorted(zip(position, speed), reverse=True): process cars from the one nearest the target backwards. A car can only be blocked by cars in front of it.
  2. time = (target - pos) / spd: when this car would arrive if nothing blocked it.
  3. If it would arrive later than the fleet directly ahead (time > stack[-1]), it never catches up: push it as a new fleet.
  4. Otherwise it catches that fleet before the target and moves at its speed from then on, so it adds nothing.
  5. len(stack) is the number of fleets. Sorting dominates: O(n log n).

Visual Walkthrough

Running it on target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]:

Cars on the road, sorted from closest to the target024681012target 1224131pos 10, speed 2: arrives at t = 1new fleet (slower than the one ahead)pos 8, speed 4: arrives at t = 1≤ 1 → joins the fleet aheadpos 5, speed 1: arrives at t = 7new fleet (slower than the one ahead)pos 3, speed 3: arrives at t = 3≤ 7 → joins the fleet aheadpos 0, speed 1: arrives at t = 12new fleet (slower than the one ahead)
Cars (circles, labelled with speed) are handled from the one closest to the target backwards. A car that would arrive no later than the fleet in front catches it and merges; a slower car starts a new fleet. Colours show the 3 fleets.
fleet 1 (pos 10, 8)fleet 2 (pos 0)fleet 3 (pos 5, 3)

Video Explanation

NeetCode — Car Fleet, LeetCode 853