There are n
cars going to the same destination along a one-lane road. The destination is target
miles away.
You are given two integer arrays position
and speed
, both of length n
, where position[i]
is the position of the ith car and speed[i]
is the speed of the ith car (in miles per hour).
A car can never pass another car ahead of it but can catch up to it and drive bumper to bumper at the same speed. The faster car may slow down to match the slower car’s speed. The distance between these two cars forms a car fleet.
Return the number of car fleets that will arrive at the destination.
Input: target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]
Output: 3
Explanation:
The cars starting at positions 10 and 8 are in forming a fleet, their arrival times at the destination are 1, 1.
The car starting at position 5 forms a fleet.
The cars starting at positions 0 and 3 are in forming a fleet, their arrival times at the destination are 8, 3.
position
and speed
aligned such that position[i]
and speed[i]
correspond to the same car?
n == position.length == speed.length
1 <= n <= 10^4
0 < position[i] < target <= 10^6
0 < speed[i] <= 10^6
With these clarifications, let’s proceed with the solution.
target
.(target - position[i]) / speed[i]
.def carFleet(target, position, speed):
cars = sorted(zip(position, speed))
fleets = 0
time_to_reach = [(target - p) / s for p, s in cars]
i = len(time_to_reach) - 1
while i >= 0:
fleets += 1
lead_time = time_to_reach[i]
while i >= 0 and time_to_reach[i] <= lead_time:
i -= 1
return fleets
# Example
target = 12
position = [10, 8, 0, 5, 3]
speed = [2, 4, 1, 1, 3]
print(carFleet(target, position, speed)) # Output: 3
O(n log n)
due to sorting the cars based on their positions.O(n)
for calculating times and processing the fleets.Overall, the time complexity is O(n log n)
due to the sorting step being the most computationally expensive operation.
This should adequately solve the problem within given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?