Imagine cars racing on a highway toward a finish line! ๐
There are n cars positioned at different miles from the start (mile 0), all heading toward a target destination. Each car has its own starting position[i] and travels at a constant speed[i] miles per hour.
Here's the twist: Cars cannot overtake each other! If a faster car catches up to a slower one, it must slow down and form a car fleet - traveling together at the speed of the slowest car in the group.
Your mission: Determine how many separate car fleets will arrive at the destination. A fleet can be a single car or multiple cars traveling together.
Key rules:
- Cars maintain their lanes (no passing)
- When cars meet, they form a fleet at the slower speed
- Even if cars meet exactly at the target, they're considered one fleet
Input & Output
Visualization
Time & Space Complexity
O(n log n) for sorting cars by position, O(n) for stack operations
O(n) for storing sorted cars and stack of fleet times
Constraints
- n == position.length == speed.length
- 1 โค n โค 105
- 0 < target โค 106
- 0 โค position[i] < target
- All values of position are unique
- 0 < speed[i] โค 106