Number of intersections between two ranges | Python3 implementation of above approach ; Function to return total number of intersections ; Maximum possible number of intersections ; Store all starting points of type1 ranges ; Store all endpoints of type1 ranges ; Starting point of type2 ranges ; Ending point of type2 ranges ; Subtract those ranges which are starting after R ; Subtract those ranges which are ending before L ; Driver Code
from bisect import bisect as upper_bound NEW_LINE def FindIntersection ( type1 , n , type2 , m ) : NEW_LINE INDENT ans = n * m NEW_LINE start = [ ] NEW_LINE end = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT start . append ( type1 [ i ] [ 0 ] ) NEW_LINE end . append ( type1 [ i ] [ 1 ] ) NEW_LINE DEDENT start = sorted ( start ) NEW_LINE start = sorted ( end ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT L = type2 [ i ] [ 0 ] NEW_LINE R = type2 [ i ] [ 1 ] NEW_LINE ans -= ( len ( start ) - upper_bound ( start , R ) ) NEW_LINE ans -= ( upper_bound ( end , L - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT type1 = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] , [ 6 , 7 ] ] NEW_LINE type2 = [ [ 1 , 5 ] , [ 2 , 3 ] , [ 4 , 7 ] , [ 5 , 7 ] ] NEW_LINE n = len ( type1 ) NEW_LINE m = len ( type2 ) NEW_LINE print ( FindIntersection ( type1 , n , type2 , m ) ) NEW_LINE