Queries to count frequencies of a given character in a given range of indices | C ++ program for the above approach ; Function to print count of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i ] [ y - ' a ' ] by 1 ; Pre - compute ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void noOfChars ( string s , char queries [ ] [ 3 ] , int q ) { int n = s . length ( ) ; int dp [ n + 1 ] [ 26 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 ] [ s [ i ] - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 ] [ j ] += dp [ i ] [ j ] ; } } for ( int i = 0 ; i < q ; i ++ ) { int l = ( int ) queries [ i ] [ 0 ] ; int r = ( int ) queries [ i ] [ 1 ] ; int c = queries [ i ] [ 2 ] - ' a ' ; cout << dp [ r ] - dp [ l - 1 ] << " ▁ " ; } } int main ( ) { string S = " aabv " ; char queries [ 2 ] [ 3 ] = { { 1 , 2 , ' a ' } , { 2 , 3 , ' b ' } } ; noOfChars ( S , queries , 2 ) ; return 0 ; }