9. Non-overlapping Intervals

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.

Example 2:

Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

Example 3:

Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Approach

Interval Scheduling Maximization

  • Selecting the intervals that start earliest is not an optimal solution, because if the earliest interval happens to be very long, accepting it would make us reject many other shorter requests.

  • Selecting the shortest intervals or selecting intervals with the fewest conflicts is also not optimal.

The following greedy algorithm does find the optimal solution:

  1. Select the interval, x, with the earliest finishing time.

  2. Remove x, and all intervals intersecting x, from the set of candidate intervals.

Solution: (Greedy)

class Solution
{
public:
    static bool comparator(vector<int> &a, vector<int> &b)
    {
        return a[1] < b[1];
    }

    int eraseOverlapIntervals(vector<vector<int>> &intervals)
    {

        sort(intervals.begin(), intervals.end(), comparator);

        int n = intervals.size();

        int i = 0, j = 1;
        int count = 0;

        while (j < n)
        {
            if (intervals[j][0] >= intervals[i][1])
            {
                i = j;
                j++;
            }
            else
            {
                count++;
                j++;
            }
        }

        return count;
    }
};

Time Complexity: O(n) Space Complexity: O(1)

Last updated