Video Stitching solution explained

Video Stitching asks for the fewest clips that together cover the whole time range from 0 to T. Sort the clips by start, then repeatedly pick, among all clips that begin inside the part already covered, the one that reaches farthest; if none reaches past the current edge there is a gap and the answer is -1. That greedy runs in O(n log n) time for the sort plus one linear sweep.

By Published 8 min read

The problem in plain words

A sports event was filmed by several cameras, and each camera saved one clip that runs from some start second to some end second. You want to build one continuous highlight reel from second 0 to second T. You can cut any clip shorter, and clips are allowed to overlap, but every moment from 0 to T must come from some clip. What is the smallest number of clips you need? If some stretch of time was never filmed, return -1.

Small examples, written for this page
ClipsTAnswerReason
[0, 4], [2, 6], [3, 9], [5, 7]92[0, 4] then [3, 9]
[0, 2], [3, 6]6-1Nothing covers the gap between 2 and 3
[1, 5], [2, 8]5-1No clip starts at 0
[0, 3], [0, 1], [1, 2], [2, 3]31The long clip alone is enough
[0, 2], [2, 5], [1, 4], [4, 7]73[0, 2], [1, 4] or [2, 5], then [4, 7]
Small examples, written for this page. Scroll sideways on a small screen.

Points to settle before coding: are clip ends inclusive in a way that matters (with whole seconds and continuous coverage, a clip ending at 4 joins one starting at 4), can a clip extend past T (yes, just trim it), can T be 0, and are all values whole numbers? If T is 0, no clip is needed and the answer is 0.

Why this is the jump game

Think of the covered range as a frontier. At the start the frontier sits at 0. Any clip that starts at or before the frontier can push it forward, to that clip's end. A clip that starts after the frontier is useless for now because it would leave a hole. So each step is: of the clips you can legally use, which pushes the frontier the farthest? That is exactly the structure of the jump game where each index lets you leap forward by some amount, and the fewest jumps to reach the end is found by always extending the farthest reach.

Why is farthest reach safe? Suppose an optimal answer picks some other clip at this step. Swapping it for the farthest-reaching clip leaves a frontier at least as far forward, and everything that clip enabled later is still enabled. The count never gets worse, so the greedy choice is part of some optimal answer.

Slow approach: DP over every second

Let need[t] be the fewest clips that cover [0, t]. need[0] is 0. For each later second t, look at every clip that starts strictly before t and ends at or after t. Using that clip means you only had to cover up to its start, so need[t] is the smallest need[start] + 1 over those clips. This is correct and easy to argue, but it touches every clip for every second, so it costs O(T · n). With T in the thousands and many clips, that is a lot of wasted work.

def fewest_clips_slow(clips, T):
    INF = float("inf")
    need = [0] + [INF] * T  # need[t]: fewest clips covering [0, t]
    for t in range(1, T + 1):
        for a, b in clips:
            if a < t <= b:
                need[t] = min(need[t], need[a] + 1)
    return -1 if need[T] == INF else need[T]
Python, O(T · n): a DP indexed by time.

Main approach: sort by start, extend the frontier

Sort the clips by start time. Keep the frontier, a pointer into the sorted list, and a count. In each round, scan forward through every clip whose start is at or before the frontier and remember the largest end among them. If that largest end does not move past the frontier, there is a gap, so return -1. Otherwise add one to the count and move the frontier to that end. Stop as soon as the frontier reaches T.

The pointer only moves forward, so across all rounds each clip is looked at once. The sweep is O(n) and the sort is O(n log n). Nothing depends on the size of T, which matters if the times are large, like milliseconds in a long recording.

def fewest_clips(clips, T):
    clips = sorted(clips)
    count, edge, i = 0, 0, 0
    while edge < T:
        reach = edge
        while i < len(clips) and clips[i][0] <= edge:
            reach = max(reach, clips[i][1])
            i += 1
        if reach == edge:
            return -1  # nothing starts inside the covered part and goes further
        count += 1
        edge = reach
    return count
Python: O(n log n) time, O(n) for the sorted copy.
function fewestClips(clips, T) {
  const sorted = [...clips].sort((x, y) => x[0] - y[0]);
  let count = 0, edge = 0, i = 0;
  while (edge < T) {
    let reach = edge;
    while (i < sorted.length && sorted[i][0] <= edge) {
      reach = Math.max(reach, sorted[i][1]);
      i++;
    }
    if (reach === edge) return -1;
    count++;
    edge = reach;
  }
  return count;
}
JavaScript: the same frontier sweep.

When T is small and bounded, an equally good variant skips the sort. Make an array of size T where slot s holds the farthest end of any clip starting at s, then sweep it with the jump-game loop. That is O(n + T) time and O(T) space.

Trace of the last example

Clips sorted by start are [0, 2], [1, 4], [2, 5], [4, 7], and T is 7. Round one: the edge is 0, only [0, 2] starts by 0, so the edge moves to 2 and the count is 1. Round two: [1, 4] and [2, 5] both start by 2; the farther end is 5, so the edge jumps to 5 and the count is 2. Round three: [4, 7] starts by 5 and ends at 7, so the edge reaches 7 and the count is 3. The edge now equals T, so the answer is 3.

Complexity

How the three methods compare
MethodTimeExtra spaceBest for
DP over every secondO(T · n)O(T)Explaining the structure; small T
Sort, then frontier sweepO(n log n)O(n)General input, large or sparse times
Bucket by start, jump-game sweepO(n + T)O(T)Small, bounded T
How the three methods compare. Scroll sideways on a small screen.

Edge cases to test

  • No clip starts at 0: the answer is -1 straight away.
  • A gap in the middle, such as clips ending at 2 and the next starting at 3.
  • One clip that already spans [0, T] or more: the answer is 1.
  • Clips that end beyond T: they count normally and are simply trimmed.
  • Clips that start after T: they never help and are never chosen.
  • Zero-length clips like [3, 3]: they cover nothing useful and must not loop forever.
  • T = 0: return 0 without picking anything.

Mistakes that cost points

  • Choosing the longest clip first. A long clip that starts in the middle can leave the opening uncovered.
  • Using a strict less-than when checking whether a clip starts inside the covered part, which treats touching clips as a gap.
  • Resetting the scan pointer every round, which turns the sweep into O(n²).
  • Forgetting the gap check, so the loop spins forever when the frontier cannot move.
  • Counting a clip as used before confirming that it actually extends the frontier.
  • Returning the count of clips scanned instead of the count of rounds.

How to explain it out loud

Fictional example

Summing up the greedy for an interviewer
Candidate
I keep a covered edge, starting at 0. Any clip that starts at or before the edge is usable, and among those I want the one that ends farthest.
Candidate
If no usable clip pushes past the edge, there is a hole and I return -1. Otherwise I count one clip and move the edge. Swapping any other choice for the farthest one never hurts, which is why the greedy is optimal.
Candidate
After sorting by start, a single pointer walks the list once, so it is O(n log n) overall.

Other problems in this set

Minimum Number of Taps to Open to Water a Garden is the closest relative: each tap becomes an interval first, and then the same frontier idea applies. For a contrast where intervals carry a value and greedy fails, see Maximum Profit in Job Scheduling. The algorithm interview questions page lists more greedy and interval topics.

Practice it with Natively

Natively can be a second pair of eyes while you drill interval greedy problems. In practice it can take a screenshot of the statement, read it, and suggest a plan you can compare with yours after a first try. It also transcribes your mock interview on your own computer, so afterward you can see whether you justified why farthest reach is safe instead of only asserting it. Find out more about an AI interview assistant on Mac and Windows.

Questions people ask

How do you solve Video Stitching?

Sort clips by start. Keep a covered edge starting at 0, and in each round take the largest end among clips that start at or before the edge. If that end does not pass the edge, return -1; otherwise count one clip and move the edge. Stop when the edge reaches T.

What is the time complexity of the greedy solution?

O(n log n) for sorting plus O(n) for the sweep, because the scan pointer only moves forward. If T is small, bucketing clips by start avoids the sort and gives O(n + T).

Why is choosing the farthest-reaching clip optimal?

Any other usable clip leaves the covered edge at the same place or earlier. Replacing it with the farthest one keeps every later option available, so the number of clips never increases.

Is Video Stitching the same as the jump game?

Structurally, yes. Each clip that starts inside the covered range is like a jump from that position, and the fewest clips equals the fewest jumps to reach the end.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP