text: InfyTQ 2019 : Find the position from where the parenthesis is not balanced | C # implementation of the approach ; Defining the string ; Storing opening braces in list lst1 ; Storing closing braces in list lst2 ; Creating an empty list lst ; Creating dictionary to map closing braces to opening ones ; If first position of string contain any closing braces return 1 ; If characters of string are opening braces then append them in a list ; When size of list is 0 and new closing braces is encountered then print its index starting from 1 ; As we encounter closing braces we map them with theircorresponding opening braces using dictionary and check if it is same as last opened braces ( last element in list ) if yes then we delete that elememt from list ; Otherwise we return the index ( starting from 1 ) at which nesting is found wrong ; At end if the list is empty it means the string is perfectly nested
code: using System ; using System . Collections . Generic ; class GFG { static void Main ( ) { string String = " { [ ( ) ] } [ ] " ; char [ ] lst1 = { ' { ' , ' ( ' , ' [ ' } ; char [ ] lst2 = { ' } ' , ' ) ' , ' ] ' } ; List < char > lst = new List < char > ( ) ; Dictionary < char , char > Dict = new Dictionary < char , char > ( ) ; Dict [ ' ) ' ] = ' ( ' ; Dict [ ' } ' ] = ' { ' ; Dict [ ' ] ' ] = ' [ ' ; int a = 0 , b = 0 , c = 0 ; if ( Array . Exists ( lst2 , element => element == String [ 0 ] ) ) { Console . WriteLine ( 1 ) ; } else { int k = 0 ; for ( int i = 0 ; i < String . Length ; i ++ ) { if ( Array . Exists ( lst1 , element => element == String [ i ] ) ) { lst . Add ( String [ i ] ) ; k = i + 2 ; } else { if ( lst . Count == 0 && Array . Exists ( lst2 , element => element == String [ i ] ) ) { Console . WriteLine ( ( i + 1 ) ) ; c = 1 ; break ; } else { if ( lst . Count > 0 && Dict [ String [ i ] ] == lst [ lst . Count - 1 ] ) { lst . RemoveAt ( lst . Count - 1 ) ; } else { a = 1 ; break ; } } } } if ( lst . Count == 0 && c == 0 ) { Console . WriteLine ( 0 ) ; b = 1 ; } if ( a == 0 && b == 0 && c == 0 ) { Console . WriteLine ( k ) ; } } } }