Cars drive toward target on a one-lane road. A car can't pass the one ahead; if it catches up, they drive together as a fleet at the slower speed. Given each car's position and speed, return how many fleets arrive.
Before you code
What decides fleets is each car's arrival time if it drove alone: (target - position) / speed. A car catches the car ahead of it exactly when it would otherwise arrive earlier.
Hints
- Sort the cars by position, closest to the target first.
- Walk them in that order with a stack of fleet arrival times. If a car's time is greater than the top, it can't catch up: it starts a new fleet, so push its time.
- Otherwise it joins the fleet ahead and is not pushed.
- The answer is the size of the stack. The times on it increase, which makes it a monotonic stack.
Production & complexity notes
When solving Car fleet on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Deques and monotonic stacks to reinforce the underlying pattern.
What it practices
Keeping only the items that still matter on a stack, from Deques and monotonic stacks.