Suppose we have a 2D list of numbers called intervals where each row represents [start, end] (inclusive) interval. For an interval [a, b] (a < b), its size is (b - a). We must add one interval to the given list such that, after merging all the intervals, we get exactly one range left. We have to find the minimum possible size of the added interval.
So, if the input is like intervals = [[15, 20],[30, 50]], then the output will be 10, as we can add the interval [20, 30] which is the smallest possible interval.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, intervals): events =  for s, e in intervals: events.append((s, 1)) events.append((e, -1)) events.sort() curr_status = 0 last = None interval = [0, 0] for time, status in events: if curr_status == 0 and last and time > last: if interval == 0: interval = last interval = time last = time curr_status += status return interval - interval ob = Solution() intervals = [[15, 20],[30, 50]] print(ob.solve(intervals))
[[15, 20],[30, 50]]