Program to find overlapping intervals and return them in ascending order in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of closed intervals and another list of intervals. Individually, each list is non-overlapping and they are sorted in non-decreasing order. We have to find the overlap of the two intervals sorted in non-decreasing order.

So, if the input is like inv1 = [[50, 100],[190, 270],[310, 330]] inv2 = [[40, 120],[180, 190]], then the output will be [[50, 100], [190, 190]]

To solve this, we will follow these steps −

  • ans := a new list
  • i := 0, j := 0
  • while i < size of A and j < size of B, do
    • if start <= end, then
      • insert interval [start, end] into ans
    • if A[i, 1] < B[j, 1], then
      • i := i + 1
    • otherwise,
      • j := j + 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A, B):
      ans = []
      i = 0
      j = 0
      while i < len(A) and j < len(B):
         start = max(A[i][0], B[j][0])
         end = min(A[i][1], B[j][1])
         if start <= end:
            ans.append([start, end])
            if A[i][1] < B[j][1]:
               i += 1
            else:
               j += 1
         return ans
ob = Solution()
inv1 = [[50, 100],[190, 270],[310, 330]]
inv2 = [[40, 120],[180, 190]]
print(ob.solve(inv1, inv2))

Input

[[50, 100],[190, 270],[310, 330]], [[40, 120],[180, 190]]

Output

[[50, 100], [190, 190]]
raja
Published on 19-Nov-2020 06:26:11
Advertisements