Program to find one minimum possible interval to insert into an interval list in Python


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 −

  • events := a new list
  • for each start and end time s, e in intervals, do
    • insert (s, 1) at the end of events
    • insert (e, -1) at the end of events
  • sort the list events
  • curr_status := 0, last := null
  • interval := a pair [0, 0]
  • for each pair (time, status) in events, do
    • if curr_status is same as 0 and last and time > last, then
      • if interval[0] is same as 0, then
        • interval[0] := last
      • interval[1] := time
    • last := time
    • curr_status := curr_status + status
  • return interval[1] - interval[0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

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] == 0:
               interval[0] = last
            interval[1] = time
         last = time
         curr_status += status
      return interval[1] - interval[0]
ob = Solution()
intervals = [[15, 20],[30, 50]] print(ob.solve(intervals))

Input

[[15, 20],[30, 50]]

Output

10

Updated on: 19-Oct-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements