Merge Intervals

Merge Intervals

Problem

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

For example:

Input: intervals =[[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6]
overlaps, merge them into [1,6].
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are 
considered overlapping.

Thought Process

Solution

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        res = []
        intervals = sorted(intervals)
        
        if len(intervals) < 2:
            return intervals
        
        curr = intervals[0]
        for i in range(1,len(intervals)):
            nextI = intervals[i]
            if curr[1] < nextI[0]:
                res.append(curr)
                curr = nextI
            else:
                curr[1] = max(curr[1],nextI[1])
        res.append(curr)
        return res
        
        
#We have to sort the intervals on their start time

#For intervals that are overlapping that means
            b.start <= a.end
            
#Time: O(n * log n) since we have to sort and iterate
#Space: O(n) for the return list

Last updated

Was this helpful?