#3635
Earliest Finish Time for Land and Water Rides II
MediumArrayTwo PointersBinary SearchGreedySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n log n + m log m)Space O(n + m)
Sort both ride types by start time. Use prefix and suffix arrays to efficiently calculate the earliest finish time for both ride orders.
⚙️
Algorithm
3 steps- 1Step 1: Sort land and water rides by start time.
- 2Step 2: Create prefix minimums for land ride finish times and suffix minimums for water ride finish times.
- 3Step 3: Calculate the minimum finish time for both orders using the prefix and suffix arrays.
solution.py13 lines
1def earliestFinish(landStart, landDuration, waterStart, waterDuration):
2 land = sorted(zip(landStart, landDuration))
3 water = sorted(zip(waterStart, waterDuration))
4 landFinish = [0] * len(land)
5 waterFinish = [0] * len(water)
6 for i in range(len(land)):
7 landFinish[i] = land[i][0] + land[i][1] if i == 0 else max(landFinish[i-1], land[i][0] + land[i][1])
8 for i in range(len(water)-1, -1, -1):
9 waterFinish[i] = water[i][0] + water[i][1] if i == len(water)-1 else min(waterFinish[i+1], water[i][0] + water[i][1])
10 minFinish = float('inf')
11 for i in range(len(land)):
12 minFinish = min(minFinish, max(landFinish[i], waterFinish[i]))
13 return minFinishℹ
Complexity note: Sorting the rides takes O(n log n) and O(m log m), and the subsequent calculations are linear.
- 1Sort rides by start time to streamline calculations.
- 2Use prefix and suffix arrays to avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.