Store the frequency of the characters
for ( int i = 0 ; i < A . length ( ) ; i ++ ) { S [ A [ i ] - ' a ' ] . push_back ( i ) ; } int low = 0 ; for ( int i = 0 ; i < B . length ( ) ; i ++ ) { auto it = lower_bound ( S [ B [ i ] - ' a ' ] . begin ( ) , S [ B [ i ] - ' a ' ] . end ( ) , low ) ;