CodingNodes / Stack / Car Fleet System design Space play · ←→ step · R restart

Problem

Cars drive along a one-lane road toward a destination at mile target. Car k starts at mile position[k] and drives at speed[k] miles per hour. All positions are different.

Cars cannot overtake. When a faster car reaches a slower one ahead of it, it slows down and the two drive on together. A group of cars moving together like this is a fleet (a single car is also a fleet). Cars that meet exactly at the target count as one fleet.

Return how many fleets arrive at the target.

Constraints

  • 1 ≤ position.length = speed.length ≤ 100000
  • 0 < target ≤ 1000000
  • 0 ≤ position[k] < target, all positions distinct
  • 0 < speed[k] ≤ 1000000

Examples: pick one to animate

Solutions

TimeO(n log n) SpaceO(n)

Time: Sorting the n cars by position costs O(n log n). The pass after it is O(n), with one push at most per car.

Space: The sorted copy of the cars and the stack each hold up to n entries.

Sort cars from nearest the target to farthest. Work out when each would arrive alone. If a car would arrive no later than the fleet just ahead (the stack top), it catches up and merges. Otherwise it leads a new fleet: push its time. The stack size is the answer.