def merge_intervals(intervals):
# Sort the given intervals with respect to their start times
intervals.sort()
# Initialize the output list with the first interval
output = []
output.append([intervals[0][0], intervals[0][1]])
# Iterate over each interval starting from the second one
for i in range(1, len(intervals)):
# Get the last interval added to the output list
last_added_interval = output[len(output) - 1]
# Extract the current interval's start and end times
cur_start = intervals[i][0]
cur_end = intervals[i][1]
# Get the end time of the last interval added to the output
prev_end = last_added_interval[1]
# If the current interval overlaps with the last added interval, merge them
if cur_start <= prev_end:
# Update the end time of the last interval to the maximum of both
output[-1][1] = max(cur_end, prev_end)
else:
# If there is no overlap, add the current interval to the output
output.append([cur_start, cur_end])
# Return the merged list of intervals
return output
# Driver code
def main():
all_intervals = [
[[3, 7], [4, 6], [1, 5]],
[[6, 8], [1, 5], [11, 15], [4, 6]],
[[11, 15], [3, 7], [10, 12], [6, 8]],
[[1, 5]],
[[1, 9], [3, 8], [4, 4]],
[[1, 2], [8, 8], [3, 4]],
[[1, 5], [1, 3]],
[[1, 5], [6, 9]],
[[0, 0], [1, 18], [1, 3]]
]
for i in range(len(all_intervals)):
print(i + 1, ". Intervals to merge:\t ", all_intervals[i], sep="")
output = merge_intervals(all_intervals[i])
print(" Merged intervals:\t", output)
print("-"*100)
if __name__ == '__main__':
main()