Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | javascript 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
function KthCharacter ( s , t , k ) { var n = s . length ; var m = t . length ; var first = 1 ; var second = 2 ; var output = ' ' ; while ( k > 0 ) { if ( k > first * n ) { var x = first * n ; k = k - x ; first = first + 2 ; if ( k > second * m ) { var y = second * m ; k = k - y ; second = second + 2 ; } else { var ind = k % m ; ind -- ; if ( ind < 0 ) ind = m - 1 ; output = t . charAt ( parseInt ( ind ) ) ; break ; } } else { var ind = k % n ; ind -- ; if ( ind < 0 ) ind = n - 1 ; output = s . charAt ( parseInt ( ind ) ) ; break ; } } return output ; } var S1 = " " , S2 = " " ; var k = 4 ; var ans = KthCharacter ( S1 , S2 , k ) ; document . write ( ans ) ;