Program to find intervals that do not intersect the cut interval in Python


Suppose we have a sorted and disjoint intervals list and another list cut, that represents an interval. We have to delete all parts of intervals that are intersecting with cut interval, and return the new list.

So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]] cut = [8, 46], then the output will be [[2, 8], [46, 61]]

To solve this, we will follow these steps −

  • cut_start, cut_end := cut
  • ans := a new list
  • for each start, end in intervals, do
    • if maximum of cut_start and start < minimum of end and cut_end, then
      • if start < cut_start, then
        • insert interval [start, cut_start] into ans
      • if end > cut_end, then
        • insert interval [cut_end, end] into ans
    • otherwise,
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, intervals, cut):
   cut_start, cut_end = cut
   ans = []
   for start, end in intervals:
      if max(cut_start, start) < min(end, cut_end):
         if start < cut_start:
            ans.append([start, cut_start])
            if end > cut_end:
               ans.append([cut_end, end])
         else:
            ans.append([start, end])
      return ans
ob = Solution()
intervals = [[2, 11],[13, 31],[41, 61]] cut = [8, 46]
print(ob.solve(intervals, cut))

Input

[[2, 11],[13, 31],[41, 61]], [8, 46]

Output

[[2, 8], [46, 61]]

Updated on: 19-Nov-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements