Queries to count frequencies of a given character in a given range of indices | Java 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 ; Number of queries ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call
import java . io . * ; class GFG { static void noOfChars ( String s , char [ ] [ ] queries ) { int n = s . length ( ) ; int dp [ ] [ ] = new int [ n + 1 ] [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 ] [ s . charAt ( i ) - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 ] [ j ] += dp [ i ] [ j ] ; } } int q = queries . length ; 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 ' ; System . out . print ( dp [ r ] - dp [ l - 1 ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { String S = " aabv " ; char queries [ ] [ ] = new char [ ] [ ] { { 1 , 2 , ' a ' } , { 2 , 3 , ' b ' } } ; noOfChars ( S , queries ) ; } }