Store the frequency of the characters
for ( int i = 0 ; i < A . Length ; i ++ ) { S [ A [ i ] - ' a ' ] . Add ( i ) ; } int low = 0 ; for ( int i = 0 ; i < B . Length ; i ++ ) { List < int > indexes = S [ B [ i ] - ' a ' ] ; int it = lower_bound ( indexes , low ) ;