Store the frequency of the characters
for ( int i = 0 ; i < A . length ( ) ; i ++ ) { S . get ( A . charAt ( i ) - ' a ' ) . add ( i ) ; } int low = 0 ; for ( int i = 0 ; i < B . length ( ) ; i ++ ) { List < Integer > indexes = S . get ( B . charAt ( i ) - ' a ' ) ; int it = lower_bound ( indexes , low ) ;