text: Check if any K ranges overlap at any point | C # implementation of the approach ; 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: using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static bool kOverlap ( List < Tuple < int , int > > pairs , int k ) { List < Tuple < int , int > > vec = new List < Tuple < int , int > > ( ) ; for ( int i = 0 ; i < pairs . Count ; i ++ ) { vec . Add ( new Tuple < int , int > ( pairs [ i ] . Item1 , - 1 ) ) ; vec . Add ( new Tuple < int , int > ( pairs [ i ] . Item2 , 1 ) ) ; } vec . Sort ( ) ; Stack st = new Stack ( ) ; for ( int i = 0 ; i < vec . Count ; i ++ ) { Tuple < int , int > cur = vec [ i ] ; if ( cur . Item2 == - 1 ) { st . Push ( cur ) ; } else { st . Pop ( ) ; } if ( st . Count >= k ) { return true ; } } return false ; } public static void Main ( params string [ ] args ) { List < Tuple < int , int > > pairs = new List < Tuple < int , int > > ( ) ; pairs . Add ( new Tuple < int , int > ( 1 , 3 ) ) ; pairs . Add ( new Tuple < int , int > ( 2 , 4 ) ) ; pairs . Add ( new Tuple < int , int > ( 3 , 5 ) ) ; pairs . Add ( new Tuple < int , int > ( 7 , 10 ) ) ; int n = pairs . Count , k = 3 ; if ( kOverlap ( pairs , k ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }