Car Fleet

Stacks & Monotonic Stacks, problem 6 of 7

Car Fleet

Medium

LC #853

monotonic stacksorting

Not attempted yet

n cars drive along a one-lane road toward a destination at mile target. Car i starts at mile position[i] and drives at speed[i] miles per hour.

Cars can't overtake. When a faster car catches up with a slower one ahead, it slows down and they continue together as one fleet (at the slower speed). A car that catches up exactly at the destination also joins that fleet. A single car on its own is a fleet too.

Return how many fleets arrive at the destination.

Example 1

Input: target = 12,
       position = [10,8,0,5,3],
       speed = [2,4,1,1,3]
Output: 3
Explanation: cars at 10 and 8 meet at 12;
the car at 0 arrives alone; cars at 5
and 3 meet at mile 6.

Example 2

Input: target = 10, position = [3], speed = [3]
Output: 1

Example 3

Input: target = 100,
       position = [0,2,4],
       speed = [4,2,1]
Output: 1

Constraints

  • 1 <= n <= 10^5
  • 0 <= position[i] < target <= 10^6
  • all positions are different
  • 1 <= speed[i] <= 10^6

Python

Loading draft…

Test results

9 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 6 hidden

Run examples, then submit all tests.