Skip to content
Decoder

Car Fleet

Medium

Problem

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. A car **can never pass** the car in front of it: if it catches up, it slows down and the two travel together at the slower speed from then on.

Cars travelling together form a fleet. A single car on its own is also a fleet. If a car catches a fleet exactly at the destination, it still counts as part of that fleet. 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

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

In the first example the cars at 10 and 8 meet at mile 12, the car at 0 never catches anyone, and the cars at 5 and 3 meet at mile 6.

Constraints

  • n == position.length == speed.length
  • 1 <= n <= 10^5
  • 0 < target <= 10^6
  • 0 <= position[i] < target, and all positions are unique.
  • 0 < speed[i] <= 10^6

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.