#853
Car Fleet
MediumArrayStackSortingMonotonic StackSortingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach sorts the cars by their starting positions and calculates the time to reach the target. By iterating from the back, we can efficiently count fleets based on the time taken to reach the target.
⚙️
Algorithm
3 steps- 1Step 1: Pair each car's position with its time to reach the target and sort them by position in descending order.
- 2Step 2: Initialize a counter for fleets and a variable to track the last time taken to reach the target.
- 3Step 3: Iterate through the sorted list and compare each car's time with the last recorded time. If it's greater, it forms a new fleet.
solution.py16 lines
1# Full working Python code
2
3def car_fleet(target, position, speed):
4 times = [(target - p) / s for p, s in zip(position, speed)]
5 cars = sorted(zip(position, times), reverse=True)
6 fleets = 0
7 last_time = 0
8
9 for pos, time in cars:
10 if time > last_time:
11 fleets += 1
12 last_time = time
13 return fleets
14
15# Example usage
16print(car_fleet(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3]))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) because we store the times in an array.
- 1Cars that reach the target at the same time form a fleet.
- 2Sorting by position allows us to efficiently determine fleet formation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.