Menu
CoddyTech

Car Fleet

MediumStackSortingpython iconjava iconcpp iconc iconjs icon+10

Cars drive along a one-lane road toward mile target. Car i starts at mile position[i] and drives at speed[i] miles per hour. No car can pass another: a car that catches up with a slower one stays right behind it, and from then on the two move together at the slower speed as one fleet.

A single car is a fleet too, and a car that reaches a fleet exactly at the destination joins it. Return the number of fleets that arrive at the destination.

Function

carFleet(target: integer, position: integer-array, speed: integer-array) → integer
targetinteger
the mile where every car is heading
positioninteger-array
the starting mile of each car
speedinteger-array
the speed of each car, in miles per hour
Returnsinteger
the number of fleets that reach the destination

Constraints

  • n == position.length == speed.length
  • 1 ≤ n ≤ 104
  • 1 ≤ target ≤ 106
  • 0 ≤ position[i] < target
  • 1 ≤ speed[i] ≤ 106
  • All positions are different.

Examples

Input
target = 20position = [14, 2, 8, 17, 0]speed = [3, 6, 4, 1, 2]
Output
2
Explanation
Alone, the cars at miles 17, 14, 8 and 2 need 3, 2, 3 and 3 hours, so 14 catches 17 and the other two reach them at mile 20. The car at 0 needs 10 hours and arrives alone.
challenge icon

Follow-up

The positions are integers below target. Can you count the fleets in O(n + target) time, without a comparison sort?

Reset code
def carFleet(target, position, speed):
    # Write code here

Test #1

Test #2

Test #3

Arguments

target = 20
position = [14, 2, 8, 17, 0]
speed = [3, 6, 4, 1, 2]

Expected Output

2