Car Fleet

35 min · carFleet()

The fastest car doesn't always arrive alone. If traffic ahead is slower, speed turns into waiting.

You're given a destination coordinate target and two matching arrays. Car i starts at position[i] and moves toward the destination at speed[i]. Every starting position is different and lies before target.

When a car catches a slower car or group ahead, they become a fleet — one unit that continues at the speed of its slowest member. Cars never pass. Return how many fleets reach target.

A few ground rules:

  • A catch that happens exactly at target still produces one fleet.
  • A car keeps its given speed until it joins a fleet.
  • Arrival times may be fractional. Their intended order is exact: compare d1 / v1 and d2 / v2 by cross-multiplying d1 * v2 and d2 * v1. Ordinary real division also has a safe margin on the generated inputs.
  • The arrays describe the same cars, so their lengths are equal.

Constraints

  • 1 <= position.length == speed.length <= 100_000
  • 0 <= position[i] < target <= 1_000_000_000
  • All values in position are distinct.
  • 1 <= speed[i] <= 1_000_000

Hints

Stand at the destination

A car's solo arrival time is (target - position[i]) / speed[i]. Which car must you examine first if you want to know whether the next one catches it?

Order cars front to back

Sort by position from closest to target to farthest. A car behind joins the fleet ahead when its solo arrival time is less than or equal to that fleet's arrival time.

Keep only fleet leaders

As you scan backward along the road, record an arrival time only when it is strictly greater than the last recorded time. Those recorded times increase, and each one represents a fleet the cars ahead can't absorb.

Follow-up

Can you prove that comparing a car only with the latest fleet time is enough, even after that fleet has absorbed several faster cars?

Visible cases

Examples

Example 1

ready
Input
target = 12
position = [
  10,
  8,
  0,
  5,
  3
]
speed = [
  2,
  4,
  1,
  1,
  3
]
Expected
3
Why
the cars form fleets led from positions 10, 5, and 0

Example 2

ready
Input
target = 10
position = [
  6,
  8
]
speed = [
  3,
  2
]
Expected
2
Why
the car at 6 reaches the target later, so it never catches the car at 8

Example 3

ready
Input
target = 10
position = [
  0,
  4,
  8
]
speed = [
  4,
  2,
  1
]
Expected
2
Why
the car at 0 catches the slower fleet led from position 4

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite