Program to find intervals by merging target interval in Python


Suppose we have a list of non-overlapping intervals. These are sorted based on end time. We have another interval target, find final interval after merging target so that intervals are still non-overlapping and sorted.

So, if the input is like intervals = [[1, 15],[25, 35],[75, 90]], target = [10, 30], then the output will be [[1, 35], [75, 90]] as first two intervals [1, 15] and [25, 35] are merged.

To solve this, we will follow these steps −

  • insert target at the end of iv

  • sort iv based on start time

  • res := a new list with first interval

  • i := 1

  • while i < size of iv, do

    • if start time of iv[i] <= end time of last interval of res, then

      • end time of last interval of res = maximum of (end time of last interval of res and end time of iv[i])

    • otherwise,

      • insert iv[i] at the end of res

    • i := i + 1

  • return res

Example (Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def solve(self, iv, target):
      iv.append(target)
      iv.sort(key=lambda x: x[0])
      res = [iv[0]]
      i = 1
      while i < len(iv):
         if iv[i][0] <= res[-1][1]:
            res[-1][1] = max(res[-1][1], iv[i][1])
         else:
            res.append(iv[i])
         i += 1
      return res
ob = Solution()
intervals = [
   [1, 15],
   [25, 35],
   [75, 90]
]
target = [10, 30]
print(ob.solve(intervals, target))

Input

[[1, 15],[25, 35],[75, 90]], [10, 30]

Output

[[1, 35], [75, 90]]

Updated on: 22-Dec-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements