Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Java program to solve the above approach ; storing length ; variables for temporary strings of s and t ; final output variable ; if k is greater than even after adding string ' s ' ' first ' times ( let ' s ▁ call ▁ it ▁ x ) ▁ we ' ll subtract x from k ; incrementing first by 2 , as said in problem statement ; if k is greater than even after adding string ' t ' ' second ' times ( let ' s ▁ call ▁ it ▁ y ) ▁ we ' ll subtract y from k ; incrementing second by two as said in problem statement ; if k is smaller than y , then the character will be at position k % m . ; returning character at k index ; if k is smaller than x , then the character is at position k % n ; returning character at k index ; Driver code
import java . io . * ; class GFG { static char KthCharacter ( String s , String t , long k ) { long n = s . length ( ) ; long m = t . length ( ) ; long first = 1 ; long second = 2 ; char output = ' ? ' ; while ( k > 0 ) { if ( k > first * n ) { long x = first * n ; k = k - x ; first = first + 2 ; if ( k > second * m ) { long y = second * m ; k = k - y ; second = second + 2 ; } else { long ind = k % m ; ind -- ; if ( ind < 0 ) ind = m - 1 ; output = t . charAt ( ( int ) ind ) ; break ; } } else { long ind = k % n ; ind -- ; if ( ind < 0 ) ind = n - 1 ; output = s . charAt ( ( int ) ind ) ; break ; } } 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 ) ; } }