Car Fleet
- 2 min read
- Stacks
- LC-Medium
Solution
-
First, sort by position, because not sorting them doesn't give us any useful information
-
Then, we check which cars can become a fleet. How?
- If a car that's behind a car arrives at the target destination BEFORE or AT the same time as the car ahead of it, they can become a fleet.
-
Let's take the blue and the green car above. The blue car's time to arrive at target is 2.5s, and for green it's 3. Since our condition specified above the image is true, it means they will become a fleet.
- When this happens, we can REMOVE one car. WHY?
- In a fleet, since all cars move at the same speed, we only need to consider one car.
- But which car do we keep?
- We always keep the one that's ahead because remember, the speed of the fleet is determined by the car that's in front. Blue's speed will be reduced to green's speed. So we don't even have to consider the blue car anymore.
- If we don't remove blue, it'll be hard for calculation later on because we have to change the speed blue from it's initial speed to green's speed.. it's just messy. It's much easier if we just remove it entirely and not consider it
-
We go from right to left, due to the above "restrictions"
-
We maintain a stack, initially only the rightmost car is on the stack
-
Then we go through the cars, and initially add them to the stack
-
Then we compare the values on the stack and see if they can form a fleet, and if they do, we remove the car at the top of the stack, effectively combining them into a single fleet
-
At the end, the number of fleets that arrive is equal to the number of elements on the stack
| Time | Space | Explanation |
|---|
O(n log n) | O(n) | |
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
pair = [[p, s] for p, s in zip(position, speed)]
stack = []
for p, s in sorted(pair)[::-1]:
time = (target - p) / s
stack.append(time)
if len(stack) >= 2 and stack[-1] <= stack[-2]:
stack.pop()
return len(stack)