This can be solved using a sweep algorithm. The idea is to save all the start points of the intervals from both sets in one sorted array and the end points in another sorted array, marking them with the information that they belong to that set. eg.
AB [(1, 4), (7, 9)] - [(3,5)] A: start:[1,7] end:[4,9], B: start:[3]end:[5] start:[(1,a),(3,b),(7,a)] end: [(4,a),(5,b),(9,a)]
Now you have two pointers to the beginning of each array. The increment of the loop is one that indicates the lower intervals of adding values ββthat begin with a character until they end with b or a. for example for above we will repeat the points in this order
(1,a) (3,b) (4,a) (5,b) (7,a) (9,a)
This leads to a linear solution in the number of intervals.
Fud
source share