Store the number of closing brackets at each index
for i in range ( l - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT close [ i ] = close [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT close [ i ] = close [ i + 1 ] NEW_LINE DEDENT DEDENT