Video Stitching — LeetCode 1024 Python Solution

MediumGreedyArrayDynamic Programming
Problem
#1024
Pattern
Greedy
Reading time
3 min

The 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.

Example

Input
clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10
Output
3
Explanation
We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.

Python solution

Python
class Solution:
    def videoStitching(self, clips: List[List[int]], time: int) -> int:
        last = [0] * time
        for a, b in clips:
            if a < time:
                last[a] = max(last[a], b)
        ans = mx = pre = 0
        for i, v in enumerate(last):
            mx = max(mx, v)
            if mx <= i:
                return -1
            if pre == i:
                ans += 1
                pre = mx
        return ans

Complexity

MeasureComplexity
TimeO(n+m)
SpaceO(m) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1024. Video Stitching is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1024. Video Stitching?
LeetCode 1024. Video Stitching is rated Medium on LeetCode.
What is the time complexity of LeetCode 1024. Video Stitching?
The Python solution on this page runs in O(n+m).
What is the space complexity of LeetCode 1024. Video Stitching?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1024. Video Stitching cover?
LeetCode 1024. Video Stitching is tagged Greedy, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview