SDE & MLE Prep

853. Car Fleet

Problem

n cars drive toward target on a one-lane road; car i starts at position[i] with speed[i]. A car can't pass the one ahead: when it catches up, they continue together at the slower speed as one fleet. Return how many fleets arrive at target (a car catching up exactly at target joins that fleet).

Example: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] → 3

Constraints: n ≤ 10⁵; positions are distinct.

Sort cars by position, closest to target first. Compute arrival time. A car behind that would arrive earlier or equal catches up and merges into the fleet ahead; otherwise it starts a new fleet.

Complexity: O(n log n).

class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        fleets, slowest = 0, 0.0
        for p, s in sorted(zip(position, speed), reverse=True):
            t = (target - p) / s
            if t > slowest:          # can't catch the fleet ahead
                fleets += 1
                slowest = t
        return fleets