MediumNo. 1024

Video Stitching — LeetCode 1024 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Dynamic Programming
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

PythonSolution
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

Time
O(n+m)
Space · auxiliary
O(m)

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

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0055Jump GameMedium
0122Best Time to Buy and Sell Stock IIMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium
0646Maximum Length of Pair ChainMedium

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.

Free to download. Check it runs on your machine, then pick a plan.