#3633
Earliest Finish Time for Land and Water Rides I
EasyArrayTwo PointersBinary SearchGreedySortingTwo PointersSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m + n + m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n log n + m log m + n + m)Space O(n + m)
By sorting both ride categories and using a two-pointer technique, we can efficiently find the earliest finish time without checking every combination.
⚙️
Algorithm
3 steps- 1Step 1: Create pairs of (start time, duration) for both ride types and sort them.
- 2Step 2: Use two pointers to traverse both sorted lists and calculate finish times.
- 3Step 3: Track the minimum finish time while ensuring rides are started at their opening times or later.
solution.py14 lines
1def earliestFinish(landStartTime, landDuration, waterStartTime, waterDuration):
2 land = sorted(zip(landStartTime, landDuration))
3 water = sorted(zip(waterStartTime, waterDuration))
4 min_finish_time = float('inf')
5 j = 0
6 for l_start, l_duration in land:
7 l_finish = l_start + l_duration
8 while j < len(water) and water[j][0] < l_finish:
9 j += 1
10 if j < len(water):
11 min_finish_time = min(min_finish_time, l_finish + water[j][1])
12 if j > 0:
13 min_finish_time = min(min_finish_time, max(water[j-1][0] + water[j-1][1], l_start) + l_duration)
14 return min_finish_timeℹ
Complexity note: Sorting takes O(n log n) and O(m log m), while the two-pointer traversal takes O(n + m).
- 1Both rides must be experienced, so we need to consider both orders.
- 2Sorting helps to efficiently pair rides based on their start times.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.