text: Queries to print the character that occurs the maximum number of times in a given range | C ++ program to find the sum of the addition of all possible subsets . ; Function that answers all the queries ; Length of the string ; Number of queries ; Prefix array ; Iterate for all the characters ; Increase the count of the character ; Presum array for all 26 characters ; Update the prefix array ; Answer every query ; Range ; Iterate for all characters ; Times the lowercase character j occurs till r - th index ; Subtract the times it occurred till ( l - 1 ) th index ; Max times it occurs ; Print the answer ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void solveQueries ( string str , vector < vector < int > > & query ) { int len = str . size ( ) ; int Q = query . size ( ) ; int pre [ len ] [ 26 ] ; memset ( pre , 0 , sizeof pre ) ; for ( int i = 0 ; i < len ; i ++ ) { pre [ i ] [ str [ i ] - ' a ' ] ++ ; if ( i ) { for ( int j = 0 ; j < 26 ; j ++ ) pre [ i ] [ j ] += pre [ i - 1 ] [ j ] ; } } for ( int i = 0 ; i < Q ; i ++ ) { int l = query [ i ] [ 0 ] ; int r = query [ i ] [ 1 ] ; int maxi = 0 ; char c = ' a ' ; for ( int j = 0 ; j < 26 ; j ++ ) { int times = pre [ r ] [ j ] ; if ( l ) times -= pre [ l - 1 ] [ j ] ; if ( times > maxi ) { maxi = times ; c = char ( ' a ' + j ) ; } } cout << " Query ▁ " << i + 1 << " : ▁ " << c << endl ; } } int main ( ) { string str = " striver " ; vector < vector < int > > query ; query . push_back ( { 0 , 1 } ) ; query . push_back ( { 1 , 6 } ) ; query . push_back ( { 5 , 6 } ) ; solveQueries ( str , query ) ; }