Car Fleet
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #853
Cars on a one-lane road drive toward target. Car i starts at position[i] with speed[i]. A car can't pass another: if it catches up, it slows down and they move together as a fleet. How many fleets arrive at the target?
Examples
text
target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3] → 3
target = 10, position = [3], speed = [3] → 1
target = 100, position = [0, 2, 4], speed = [4, 2, 1] → 1Hints
- Compute each car's time to reach the target if it were alone.
- Process cars from the one closest to the target backwards.
- A car behind catches up iff its solo arrival time ≤ the fleet ahead's time.
Approach
Sort cars by position descending, and compute time = (target − pos) / speed. Sweep, keeping the arrival time of the current lead fleet: if a car's time is greater, it can't catch up, so it forms a new fleet (count++, update the lead time); otherwise it merges. (A stack of fleet times expresses the same idea.) O(n log n).
Complexity
Time: O(n log n). Space: O(n).
Python solution
def carFleet(target, position, speed):
cars = sorted(zip(position, speed), reverse=True)
fleets, lead = 0, 0.0
for p, s in cars:
t = (target - p) / s
if t > lead:
fleets += 1
lead = t
return fleetsJavaScript solution
function carFleet(target, position, speed) {
const cars = position.map((p, i) => [p, speed[i]]).sort((a, b) => b[0] - a[0]);
let fleets = 0, lead = 0;
for (const [p, s] of cars) { const t = (target - p) / s; if (t > lead) { fleets++; lead = t; } }
return fleets;
}