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.
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?