Non overlapping intervals

August 7, 2022

intervals

Problem URL: Non overlapping intervals

First we will sort the intervals. Then we will iterate through all the intervals, compare if we have any collision between 2 consecutive interval, if yes, then we will count that, then after the iteration is done, return that count.

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort()
        res = 0
        prevEnd = intervals[0][1]
        for start, end in intervals[1:]:
            if start >= prevEnd:
                prevEnd = end
            else:
                res += 1
                prevEnd = min(end, prevEnd)
        return res

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