text: Check if any K ranges overlap at any point | Function that returns true if any k segments overlap at any point ; Vector to store the starting point and the ending point ; Starting points are marked by - 1 and ending points by + 1 ; Sort the vector by first element ; Stack to store the overlaps ; Get the current element ; If it is the starting point ; Push it in the stack ; It is the ending point ; Pop an element from stack ; If more than k ranges overlap ; Driver Code
code: def kOverlap ( pairs : list , k ) : NEW_LINE INDENT vec = list ( ) NEW_LINE for i in range ( len ( pairs ) ) : NEW_LINE INDENT vec . append ( ( pairs [ 0 ] , - 1 ) ) NEW_LINE vec . append ( ( pairs [ 1 ] , 1 ) ) NEW_LINE DEDENT vec . sort ( key = lambda a : a [ 0 ] ) NEW_LINE st = list ( ) NEW_LINE for i in range ( len ( vec ) ) : NEW_LINE INDENT cur = vec [ i ] NEW_LINE if cur [ 1 ] == - 1 : NEW_LINE INDENT st . append ( cur ) NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT if len ( st ) >= k : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pairs = list ( ) NEW_LINE pairs . append ( ( 1 , 3 ) ) NEW_LINE pairs . append ( ( 2 , 4 ) ) NEW_LINE pairs . append ( ( 3 , 5 ) ) NEW_LINE pairs . append ( ( 7 , 10 ) ) NEW_LINE n = len ( pairs ) NEW_LINE k = 3 NEW_LINE if kOverlap ( pairs , k ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT