Sponsored
Sponsored
The key to solving this problem is to first sort the intervals based on the starting time. Once sorted, we can iterate over the intervals and merge them if they overlap. Two intervals overlap if the start of the current interval is less than or equal to the end of the previous interval.
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(n), required for the output array.
1def merge(intervals):
2 intervals.sort(key=lambda x: x[0])
3 merged = []
4 for interval in intervals:
5 if not merged or merged[-1][1] < interval[0]:
6 merged.append(interval)
7 else:
8 merged[-1][1] = max(merged[-1][1], interval[1])
9 return mergedIn Python, the built-in sort function is used to arrange the intervals. We iterate through and merge the overlapping intervals.
This method involves sorting first and directly inserting into the result list, verifying overlap in consecutive intervals.