16 · Stacks & Monotonic Stack

#853 Car Fleet

Mediumsolve on LeetCode ↗

frequently reported atGoogleAmazon

the problem

In plain words

n cars drive toward target on a one-lane road. Car i starts at position[i] with speed[i]. A car can't pass the car ahead; when it catches up it slows down and they move together as one fleet. A car that catches a fleet exactly at the target also joins it. How many fleets arrive?

in target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]

out 3

Cars at 10 and 8 meet at 12. The car at 0 is alone. Cars at 5 and 3 meet at 6.

in target = 10, position = [3], speed = [3]

out 1

in target = 100, position = [0,2,4], speed = [4,2,1]

out 1

Alone they would arrive at times 25, 49 and 96. The car at 4 is the slowest and leads; the two cars behind catch it.

  • 1 ≤ n ≤ 10⁵
  • 0 < target ≤ 10⁶
  • 0 ≤ position[i] < target, all distinct
  • 0 < speed[i] ≤ 10⁶

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #739
      Daily Temperatures
      Mediumin Stacks
    2. #735
      Asteroid Collision
      Mediumin Stacks