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 element 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string String = " { [ ( ) ] } [ ] " ; vector < char > lst1 = { ' { ' , ' ( ' , ' [ ' } ; vector < char > lst2 = { ' } ' , ' ) ' , ' ] ' } ; vector < char > lst ; int k ; map < char , char > Dict ; Dict . insert ( pair < int , int > ( ' ) ' , ' ( ' ) ) ; Dict . insert ( pair < int , int > ( ' } ' , ' { ' ) ) ; Dict . insert ( pair < int , int > ( ' ] ' , ' [ ' ) ) ; int a = 0 , b = 0 , c = 0 ; if ( count ( lst2 . begin ( ) , lst2 . end ( ) , String [ 0 ] ) ) { cout << 1 << endl ; } else { for ( int i = 0 ; i < String . size ( ) ; i ++ ) { if ( count ( lst1 . begin ( ) , lst1 . end ( ) , String [ i ] ) ) { lst . push_back ( String [ i ] ) ; k = i + 2 ; } else { if ( lst . size ( ) == 0 && ( count ( lst2 . begin ( ) , lst2 . end ( ) , String [ i ] ) ) ) { cout << ( i + 1 ) << endl ; c = 1 ; break ; } else { if ( Dict [ String [ i ] ] == lst [ lst . size ( ) - 1 ] ) { lst . pop_back ( ) ; } else { break ; cout << ( i + 1 ) << endl ; a = 1 ; } } } } if ( lst . size ( ) == 0 && c == 0 ) { cout << 0 << endl ; b = 1 ; } if ( a == 0 && b == 0 && c == 0 ) { cout << k << endl ; } } return 0 ; }