Interval List Intersections in C++


Suppose we have two lists of closed intervals, here each list of intervals is pairwise disjoint and in sorted order. We have ti find the intersection of these two interval lists.

We know that the closed interval [a, b] is denoted as a <= b. the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval.

So if the input is like A = [[0,2],[5,10],[13,23],[24,25]] and B = [[1,5],[8,12],[15,24],[25,27]], then the output will be [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]].

To solve this, we will follow these steps −

  • Make a list res, set I := 0 and j := 0

  • Define a method called intersect(), this will take a and b −

  • if a[0] <= b[0] and a[1] >= b[0], then return true,

  • otherwise when b[0] <= a[0] and b[1] >= a[0], then return true, otherwise return False

  • while I < size of A and j > size of B

    • if intersect(A[i], B[i])

      • temp := max of A[i, 0], B[j, 0], minimum of A[i,1] and B[j, 1]

      • A[i,0] := temp[1] + 1, B[j,0] := temp[1] + 1

      • if A[i,0] > A[i,1] or A[i,1] <= temp[0], then increase i by 1

      • if B[j,0]>B[j,1] or B[j,1] <= temp[0]: then increase j by 1

      • result.append(temp)

      • Skip for the next iteration

    • if A[i,0] > B[j, 1], then increase j by 1, otherwise increase i by 1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def intervalIntersection(self, A, B):
   result = []
   i,j = 0,0
   while i < len(A) and j < len(B):
      if self.intersect(A[i],B[j]):
         temp = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])]
         A[i][0]=temp[1]+1
         B[j][0] = temp[1]+1
         if A[i][0] > A[i][1] or A[i][1] <= temp[0]:
            i+=1
         if B[j][0]>B[j][1] or B[j][1] <= temp[0]:
            j+=1
         result.append(temp)
         continue
      if A[i][0]>B[j][1]:
         j+=1
      else:
         i+=1
   return result
   def intersect(self,a,b):
      if a[0]<=b[0] and a[1]>=b[0]:
         return True
      if b[0]<=a[0] and b[1] >=a[0]:
         return True
      return False
ob = Solution()
print(ob.intervalIntersection([[0,2],[5,10],[13,23],[24,25]],[[1,5],[8,12],[15,24],[25,27]]))

Input

[[0,2],[5,10],[13,23],[24,25]]
[[1,5],[8,12],[15,24],[25,27]]

Output

[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]

Updated on: 02-May-2020

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements