Problem statement

https://binarysearch.com/problems/Merge-New-Interval/

Solution

Equal to Leetcode 0057. Insert Interval.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, intervals, I):
        res, i = [], -1
        for i, (x, y) in enumerate(intervals):
            if y < I[0]:
                res.append([x, y])
            elif I[1] < x:
                i -= 1
                break
            else:
                I[0] = min(I[0], x)
                I[1] = max(I[1], y)
                
        return res + [I] + intervals[i+1:]