Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Java Program to implement the above approach include " bits / stdJava . h " ; Function to find the kth greatest character from the strijng ; Sorting the String in non - increasing Order ; Function to print the K - th character from the subString S [ l ] . . S [ r ] ; 0 - based indexing ; SubString of str from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of str by the character s ; Index of S to be updated . ; Character to be replaced at index in S ; Driver Code ; Given String ; Count of queries ; Queries
import java . util . * ; class GFG { static char find_kth_largest ( char [ ] str , int k ) { Arrays . sort ( str ) ; reverse ( str ) ; return str [ k - 1 ] ; } static char [ ] reverse ( char a [ ] ) { int i , n = a . length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static char printCharacter ( String str , int l , int r , int k ) { l = l - 1 ; r = r - 1 ; String temp = str . substring ( l , r - l + 1 ) ; char ans = find_kth_largest ( temp . toCharArray ( ) , k ) ; return ans ; } static void updateString ( char [ ] str , int pos , char s ) { int index = pos - 1 ; char c = s ; str [ index ] = c ; } public static void main ( String [ ] args ) { String str = " abcddef " ; int Q = 3 ; System . out . print ( printCharacter ( str , 1 , 2 , 2 ) + "NEW_LINE"); updateString ( str . toCharArray ( ) , 4 , ' g ' ) ; System . out . print ( printCharacter ( str , 1 , 5 , 4 ) + "NEW_LINE"); } }