Video Stitching in C++


Suppose we have a series of video clips from a sporting event that lasted T seconds. Now these video clips can be overlapping with each other and have varied lengths. Here each video clip clips[i] is an interval − it starts at clips[i][0] time and ends at clips[i][1] time. We can cut these clips into segments freely − We have to find the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]). If the task is impossible, return -1. So if the input is like [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], and T = 10, then the output will be 3, as we can take clips [0,2], [8,10] and [1,9], a total of 3 clips, then we can reconstruct the sporting event as follows, we cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which are covering the sporting event [0, 10].

To solve this, we will follow these steps −

  • Create an array v of size T + 1, and fill this with – 1

  • n := size of clips

  • for i in range 0 to n – 1

    • if clips[i, 0] > T, then skip to the next iteration

    • v[clips[i, 0]] := max of v[clips[i, 0]] and min of (clips[i, 1] and T)

  • curr := v[0]

  • if v[0] is -1, then return -1

  • i := 1, ret := 1 and next := 0

  • while curr < T and i <= n

    • while i <= curr

      • next := max of next and v[i]

      • increase i by 1

    • if next = curr and next is -1, then return -1

    • curr := next

  • return ret when curr >= T, otherwise return – 1

Let us see the following implementation to get better understanding

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int videoStitching(vector<vector<int>>& clips, int T) {
      vector <int> v(T + 1, -1);
      int n = clips.size();
      for(int i = 0; i < n; i++){
         if(clips[i][0] > T)continue;
         v[clips[i][0]] = max(v[clips[i][0]], min(clips[i][1],
         T));
      }
      int curr = v[0];
      if(v[0] == -1)return -1;
      int i = 1;
      int ret = 1;
      int next = 0;
      while(curr < T && i <= n){
         while(i <= curr){
            next = max(next, v[i]);
            i++;
         }
         if(next == curr || next == -1) return -1;
         curr = next;
         ret++;
      }
      return curr >= T? ret : -1;
   }
};
main(){
   vector<vector<int>> v1 = {{0,2},{4,6},{8,10},{1,9},{1,5},{5,9}};
   Solution ob;
   cout << (ob.videoStitching(v1, 10));
}

Input

[[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]]
10

Output

3

Updated on: 30-Apr-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements