#1024
Video Stitching
MediumArrayDynamic ProgrammingGreedyGreedySortingInterval Scheduling
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution uses a greedy approach by sorting the clips based on their start times and then iteratively selecting the clip that extends the coverage the furthest. This ensures we use the minimum number of clips to cover the entire interval.
⚙️
Algorithm
3 steps- 1Step 1: Sort the clips based on their start times.
- 2Step 2: Initialize variables for tracking the current end of coverage and the number of clips used.
- 3Step 3: Iterate through the sorted clips and extend coverage as far as possible with the fewest clips.
solution.py14 lines
1# Full working Python code
2def videoStitching(clips, time):
3 clips.sort(key=lambda x: x[0])
4 count, end, farthest = 0, 0, 0
5 i = 0
6 while end < time:
7 while i < len(clips) and clips[i][0] <= end:
8 farthest = max(farthest, clips[i][1])
9 i += 1
10 if end == farthest:
11 return -1
12 end = farthest
13 count += 1
14 return countℹ
Complexity note: The time complexity is dominated by the sorting step, which is O(n log n). The subsequent linear scan through the clips is O(n).
- 1Greedy algorithms often provide optimal solutions for interval covering problems.
- 2Sorting the intervals allows us to efficiently find the best clip to extend coverage.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.