Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Java program to solve the above approach ; initializing first and second variable as to store how many string ' s ' and string ' t ' will be appended ; storing tmp length ; if length of string tmp is greater than k , then we have reached our destination string now we can return character at index k ; appending s to tmp , f times ; appending t to tmp , s times ; extracting output character ; Driver code
import java . io . * ; class GFG { static char KthCharacter ( String s , String t , long k ) { long f = 1 ; long ss = 2 ; String tmp = " " ; int len = tmp . length ( ) ; while ( len < k ) { long tf = f ; long ts = ss ; while ( tf -- != 0 ) { tmp += s ; } while ( ts -- != 0 ) { tmp += t ; } f += 2 ; ss += 2 ; len = tmp . length ( ) ; } char output = tmp . charAt ( ( int ) k - 1 ) ; return output ; } public static void main ( String [ ] args ) { String S1 = " a " , S2 = " bc " ; int k = 4 ; char ans = KthCharacter ( S1 , S2 , k ) ; System . out . println ( ans ) ; } }