Video Stitching - Problem

You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.

Each video clip is described by an array clips where clips[i] = [start_i, end_i] indicates that the ith clip started at start_i and ended at end_i.

We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].

Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.

Input & Output

Example 1 — Basic Coverage
$ Input: clips = [[0,2],[1,9],[1,5],[3,8]], time = 5
Output: 2
💡 Note: We need clip [0,2] to cover [0,2] and clip [1,9] to cover [2,5], so minimum 2 clips are needed
Example 2 — Multiple Clips Needed
$ Input: clips = [[0,1],[1,2]], time = 5
Output: -1
💡 Note: The clips only cover [0,2] but we need to cover [0,5], making it impossible
Example 3 — Optimal Combination
$ Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,6],[5,7],[6,9]], time = 9
Output: 3
💡 Note: Use clips [0,4], [2,6], [6,9] to cover [0,9] with minimum 3 clips

Constraints

  • 1 ≤ clips.length ≤ 100
  • 0 ≤ starti ≤ endi ≤ 100
  • 1 ≤ time ≤ 100

Visualization

Tap to expand
Video Stitching - Greedy Approach INPUT Video Clips on Timeline 0 2 4 6 8 9 [0,2] [1,9] [1,5] [3,8] Target: time=5 clips = [[0,2],[1,9], [1,5],[3,8]] time = 5 Cover interval [0,5] ALGORITHM STEPS 1 Sort by start time Clips in order of start 2 Start at position 0 Find clip starting at 0 3 Greedy extension Pick max end each time 4 Check coverage Until we reach time Process: cur=0: [0,2] or [1,9] Both start at/before 0 Pick [1,9] end=9 (max) 9 >= time(5) Done! count=1 [1,9] covers [0,5] alone FINAL RESULT Optimal Coverage 0 5 9 [1,9] - Selected Output: 1 OK - Valid Only 1 clip needed [1,9] starts at 1 but [0,2] bridges 0-1 Wait: [1,9] starts at 1! Key Insight: Greedy works because we always extend coverage as far as possible. At each step, among clips that start before or at current end, pick the one with maximum end. Here [1,9] covers [0,5] since it overlaps with [0,2] at position 1. Time: O(n log n) TutorialsPoint - Video Stitching | Greedy - Maximum Coverage Extension
Asked in
Google 15 Amazon 12 Apple 8 Microsoft 6
32.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen