# 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 <= b and a >= b, then return true,

• otherwise when b <= a and b >= a, 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, B[j,0] := temp + 1

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

• if B[j,0]>B[j,1] or B[j,1] <= temp: 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],B[j]),min(A[i],B[j])]
A[i]=temp+1
B[j] = temp+1
if A[i] > A[i] or A[i] <= temp:
i+=1
if B[j]>B[j] or B[j] <= temp:
j+=1
result.append(temp)
continue
if A[i]>B[j]:
j+=1
else:
i+=1
return result
def intersect(self,a,b):
if a<=b and a>=b:
return True
if b<=a and b >=a:
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]]