Music streaming app~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1024greedy
A video editor has a pool of clips from a live event, each with a start and an end second. A highlight reel must run from second 0 to second length, built from clips that are joined one after another.
A smooth join needs a transition, so the next clip must start at least overlap seconds before the previous clip ends. The first clip must start at second 0.
The editor wants the fewest clips that cover the whole reel.
Write fewest_clips_with_overlap(clips, length, overlap).
clips[i] is [start, end] in seconds, with start <= end.overlap seconds before the previous clip ends, and ends later than it. The last clip ends at length or later.-1 if no reel exists.Input: clips = [[0,6],[6,12],[12,20],[4,10],[8,15],[3,5]], length = 20, overlap = 2
Output: 4The solution sorts the clips by start. For each join, it looks at every clip that starts at least overlap seconds before the reel ends. It takes the one that ends last.
| Reel ends at | Clips allowed to start at or before | Best clip | Count |
|---|---|---|---|
| first clip | second 0 | [0,6] |
1 |
| 6 | second 4 | [4,10] |
2 |
| 10 | second 8 | [8,15] |
3 |
| 15 | second 13 | [12,20] |
4 |
The reel now reaches second 20, so the answer is 4.
Input: clips = [[0,6],[6,12],[12,20],[4,10],[8,15],[3,5]], length = 20, overlap = 0
Output: 3With no overlap needed, a clip can start exactly where the last one ends. The clips [0,6], [6,12] and [12,20] give a reel of 3 clips.
Input: clips = [[0,6],[6,12],[12,20],[4,10],[8,15],[3,5]], length = 20, overlap = 3
Output: -1After the clip [0,6], the next clip must start by second 3. The only such clips are [0,6] itself and [3,5], and neither ends later than 6, so the reel cannot grow.
1 ≤ len(clips) ≤ 100,000, and every clip is [start, end] with 0 ≤ start ≤ end ≤ 1,000,0001 ≤ length ≤ 1,000,000 and 0 ≤ overlap ≤ 1,000,000Trying every set of clips costs 2 to the power of 100,000, and trying every order of a set is worse. After sorting, one pass over the clips costs about 100,000 steps, and sorting costs about 1,700,000.