def insert_interval(existing_intervals, new_interval): # Read the starting and ending time of the new interval, into separate variables new_start, new_end = new_interval[0], new_interval[1] print("The new interval starts at ", new_start, " and ends at ", new_end, ".", sep="") # Initialize variables to help in iterating over the existing intervals list i = 0 n = len(existing_intervals) print("There are", n, "intervals present in the list already.") # Initialize an empty list to store the output output = [] # Append all intervals that start before the new interval to the output list print("Let's start adding these intervals into our output list one by one, until we come across an overlapping interval.") print("-" * 100) while i < n and existing_intervals[i][0] < new_start: output.append(existing_intervals[i]) i = i + 1 print("The current output list of intervals without any overlapping intervals is:") print(output) # If the new interval starts after the end of the last interval appended to the output list, # just append the new interval to the output list. print("The output after merging this overlapping interval will be:") if not output or output[-1][1] < new_start: output.append(new_interval) # Otherwise merge the two intervals else: output[-1][1] = max(output[-1][1], new_end) print(output) print("-" * 100) # Driver code def main(): new_interval = [[5, 7], [8, 9], [10, 12], [1, 3], [1, 10]] existing_intervals = [ [[1, 2], [3, 5], [6, 8]], [[1, 3], [5, 7], [10, 12]], [[8, 10], [12, 15]], [[5, 7], [8, 9]], [[3, 5]] ] for i in range(len(new_interval)): print("Exiting intervals: ", existing_intervals[i], sep="") print("New interval: ", new_interval[i], sep="") output = insert_interval(existing_intervals[i], new_interval[i]) print("-"*100) if __name__ == "__main__": main()