Video Stitching

medium intervals greedy

Problem

You are given clips, each clips[i] = [start, end]. Return the minimum number of clips needed to cover the interval [0, time]. If impossible, return -1.

Inputclips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10
Output3
Pick [0,2], [1,9], [5,9] — three clips cover [0, 10].

def video_stitching(clips, time):
    clips.sort()
    n, i, count = len(clips), 0, 0
    cur_end, far = 0, 0
    while cur_end < time:
        while i < n and clips[i][0] <= cur_end:
            far = max(far, clips[i][1])
            i += 1
        if far == cur_end:
            return -1
        cur_end = far
        count += 1
    return count
function videoStitching(clips, time) {
  clips.sort((a, b) => a[0] - b[0]);
  let i = 0, count = 0, curEnd = 0, far = 0;
  while (curEnd < time) {
    while (i < clips.length && clips[i][0] <= curEnd) {
      far = Math.max(far, clips[i][1]);
      i++;
    }
    if (far === curEnd) return -1;
    curEnd = far;
    count++;
  }
  return count;
}
class Solution {
    public int videoStitching(int[][] clips, int time) {
        Arrays.sort(clips, (a, b) -> a[0] - b[0]);
        int i = 0, count = 0, curEnd = 0, far = 0;
        while (curEnd < time) {
            while (i < clips.length && clips[i][0] <= curEnd) {
                far = Math.max(far, clips[i][1]);
                i++;
            }
            if (far == curEnd) return -1;
            curEnd = far;
            count++;
        }
        return count;
    }
}
int videoStitching(vector<vector<int>>& clips, int time) {
    sort(clips.begin(), clips.end());
    int i = 0, count = 0, curEnd = 0, far = 0;
    while (curEnd < time) {
        while (i < (int)clips.size() && clips[i][0] <= curEnd) {
            far = max(far, clips[i][1]);
            i++;
        }
        if (far == curEnd) return -1;
        curEnd = far;
        count++;
    }
    return count;
}
Time: O(n log n) Space: O(1)