Store the number of closing brackets at each index
for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == ' ) ' ) close [ i ] = close [ i + 1 ] + 1 ; else close [ i ] = close [ i + 1 ] ; }