InterviewPrepKit

Home / Coding / Stack

Car Fleet

medium Original ↗
Solving tips
  • Recognize this as a sort + monotonic-stack problem in disguise: convert each car to its unobstructed arrival time (target - pos) / speed, the single number that decides its fate.
  • Key insight: a fleet's arrival time is its leader's time and joining never speeds the leader up, so process cars sorted from nearest-the-target backward and count a new fleet only when a car's time exceeds the fleet ahead.
  • Watch the comparison and precision: a car arriving at exactly the leader's time joins it, and keep the time a float (never use // integer division).
  • Target O(n log n) time (sort dominates) and O(1) extra space, since the stack only ever checks its top and collapses to a single 'slowest so far' variable.

Problem

n cars drive along a one-lane road toward a destination at mile target. Car i starts at mile position[i] (all starts distinct) and drives at speed[i] miles per hour. A car can never pass the car ahead of it: if it catches up, it slows to match and the two travel bumper-to-bumper as a single fleet from then on. A lone car is a fleet of one, and a car that catches another exactly at the target line still counts as part of that fleet.

Return how many fleets cross the target line.

Examples

  • target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]3 — the cars at 10 and 8 meet at mile 12 (one fleet); the car at 0 never catches anyone (one fleet); the cars at 5 and 3 meet at mile 6 and finish together (one fleet).
  • target = 10, position = [3], speed = [3]1 — a single car is a single fleet.
  • target = 100, position = [0, 2, 4], speed = [4, 2, 1]1 — the fastest car is last; everyone piles into the slow leader before mile 100.

Constraints

  • 1 <= n <= 10^5
  • 0 < target <= 10^6, 0 <= position[i] < target, all position[i] distinct
  • 0 < speed[i] <= 10^6

n = 10^5 rules out quadratic re-simulation; the expected solution is sort plus one linear pass — O(n log n).

Think about it first

Hint 1 Ignore blocking for a second: if nothing were in the way, car `i` would reach the target at time `(target - position[i]) / speed[i]`. Blocking can only make a car *later*, never earlier.
Hint 2 Sort cars by starting position, front of the road first. A car catches the fleet ahead if and only if its unobstructed arrival time is less than or equal to that fleet's arrival time — and joining never changes the fleet's time, because the fleet's leader stays the leader.
Hint 3 Walk the sorted cars from the front of the road toward the back, keeping a stack of fleet arrival times. For each car, if its time is `<=` the time on top of the stack it merges into that fleet (push nothing); otherwise it starts a new fleet (push its time). The answer is the stack size.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.