You are given a list of time intervals represented as an array of arrays, where each inner array contains the start and end time of an interval. The goal is to merge all overlapping intervals and return a new array containing only the non-overlapping intervals that completely cover all the original intervals.
For example:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
[1,3]
and [2,6]
overlap, so they are merged into [1,6]
. The other intervals do not overlap, so they remain as they are.Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
[1,4]
and [4,5]
overlap and are merged into [1,5]
.Write a function that takes an array of intervals as input and returns an array of merged, non-overlapping intervals. Consider edge cases such as an empty input array or a list of intervals that are already merged or do not overlap.
Constraints:
1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= starti <= endi <= 10^4
One simple way to approach this problem is to iterate through each interval and compare it with every other interval to see if they overlap. If two intervals overlap, merge them. Repeat this process until no more intervals can be merged.
This approach is not efficient but easy to understand.
A more efficient approach involves sorting the intervals based on their start times. After sorting, you can iterate through the intervals and merge overlapping intervals in a single pass.
mergedIntervals
.mergedIntervals
.mergedIntervals
, merge them.mergedIntervals
.mergedIntervals
.def merge(intervals):
if not intervals:
return []
# Sort the intervals based on start times
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# If the list of merged intervals is empty or if the current
# interval does not overlap with the last interval, append it
if not merged or interval[0] > merged[-1][1]:
merged.append(interval)
else:
# Otherwise, there is overlap, so we merge the current interval
# with the last one
merged[-1][1] = max(merged[-1][1], interval[1])
return merged