Intuition
The problem involves cars moving towards a destination along a one-lane road, and the task is to determine the number of car fleets that will arrive at the destination. A car fleet is a set of cars driving at the same position and speed, and a car can never pass another car but can catch up to it and drive bumper to bumper.
Approach
The provided solution uses a stack to keep track of the time it takes for each car to reach the destination. The main idea is to sort the cars based on their starting positions in descending order and calculate the time it takes for each car to reach the destination. If a car catches up to another car before the destination, they form a fleet.
Create pairs of (position, speed) for each car.
Sort the pairs in descending order based on the starting positions.
Iterate through the sorted pairs, calculate the time it takes for each car to reach the destination, and push it onto the stack.
If the current car catches up to the car in front of it (the time for the current car is less than or equal to the time for the car in front), pop the stack to merge the fleets.
The length of the final stack represents the number of car fleets that will arrive at the destination.
Complexity
- Time complexity:
The time complexity of this solution is O(n log n), where n is the number of cars. The dominant factor is the sorting step.
- Space complexity:
The space complexity is O(n) due to the stack storing the time for each car to reach the destination.
Code
class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
pair = [[p,s] for p,s in zip(position,speed)]
stack=[]
pair = sorted(pair)[::-1]
for p,s in pair:
stack.append((target-p)/s)
if len(stack) >= 2 and stack[-1] <= stack[-2]:
stack.pop()
return len(stack)