AlgoLounge

Car Fleet

medium

Leetcode 853. Car Fleet

There are n cars traveling to the same destination on a one-lane highway.

You are given two arrays of integers position and speed, both of length n, where:

  • position[i] is the position of the ith car (in miles)
  • speed[i] is the speed of the ith car (in miles per hour)

The destination is at position target miles.

A car cannot pass another car ahead of it. It can only catch up to another car and then drive at the same speed as the car ahead of it.

A car fleet is a non-empty set of cars driving at the same position and same speed. A single car is also considered a car fleet.

If a car catches up to a car fleet the moment the fleet reaches the destination, then the car is considered to be part of the fleet.

Return the number of different car fleets that will arrive at the destination.

Examples

Example 1

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

The cars starting at 1 (speed 3) and 4 (speed 2) become a fleet, meeting each other at 10, the destination.

Example 2

Input:  target = 10, position = [4,1,0,7], speed = [2,2,1,1]
Output: 3

The cars starting at 4 and 7 become a fleet at position 10. The cars starting at 1 and 0 never catch up to the car ahead of them. Thus, there are 3 car fleets.

Constraints

  • n == position.length == speed.length
  • 1 <= n <= 1000
  • 0 < target <= 1000
  • 0 < speed[i] <= 100
  • 0 <= position[i] < target
  • All the values of position are unique.
TypeScript
Loading editor…
List of test cases (10)
Case 1
target = 10
position = [1,4]
speed = [3,2]
Case 2
target = 10
position = [4,1,0,7]
speed = [2,2,1,1]
Case 3
target = 12
position = [10,8,0,5,3]
speed = [2,4,1,1,3]
Case 4
target = 100
position = [0,2,4]
speed = [4,2,1]
Case 5
target = 10
position = [6,8]
speed = [3,2]
Case 6
target = 10
position = [0]
speed = [1]
Case 7
target = 10
position = [8,3,7,4,6,5]
speed = [4,4,4,4,4,4]
Case 8
target = 20
position = [6,2,17]
speed = [3,9,2]
Case 9
target = 13
position = [10,4,1,8,9]
speed = [3,4,5,4,3]
Case 10
target = 15
position = [0,3,6,9,12]
speed = [5,4,3,2,1]