text: InfyTQ 2019 : Find the position from where the parenthesis is not balanced | 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: string = " { [ ( ) ] } [ ] " NEW_LINE lst1 = [ ' { ' , ' ( ' , ' [ ' ] NEW_LINE lst2 = [ ' } ' , ' ) ' , ' ] ' ] NEW_LINE lst = [ ] NEW_LINE Dict = { ' ) ' : ' ( ' , ' } ' : ' { ' , ' ] ' : ' [ ' } NEW_LINE a = b = c = 0 NEW_LINE if string [ 0 ] in lst2 : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , len ( string ) ) : NEW_LINE INDENT if string [ i ] in lst1 : NEW_LINE INDENT lst . append ( string [ i ] ) NEW_LINE k = i + 2 NEW_LINE DEDENT else : NEW_LINE INDENT if len ( lst ) == 0 and ( string [ i ] in lst2 ) : NEW_LINE INDENT print ( i + 1 ) NEW_LINE c = 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT if Dict [ string [ i ] ] == lst [ len ( lst ) - 1 ] : NEW_LINE INDENT lst . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( i + 1 ) NEW_LINE a = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if len ( lst ) == 0 and c == 0 : NEW_LINE INDENT print ( 0 ) NEW_LINE b = 1 NEW_LINE DEDENT if a == 0 and b == 0 and c == 0 : NEW_LINE INDENT print ( k ) NEW_LINE DEDENT DEDENT