Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Python 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
def KthCharacter ( s , t , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = len ( t ) NEW_LINE first = 1 NEW_LINE second = 2 NEW_LINE output = ' ? ' NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( k > first * n ) : NEW_LINE INDENT x = first * n NEW_LINE k = k - x NEW_LINE first = first + 2 NEW_LINE if ( k > second * m ) : NEW_LINE INDENT y = second * m NEW_LINE k = k - y NEW_LINE second = second + 2 NEW_LINE DEDENT else : NEW_LINE INDENT ind = k % m NEW_LINE ind -= 1 NEW_LINE if ( ind < 0 ) : NEW_LINE INDENT ind = m - 1 NEW_LINE DEDENT output = t [ ind ] NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ind = k % n NEW_LINE ind -= 1 NEW_LINE if ( ind < 0 ) : NEW_LINE INDENT ind = n - 1 NEW_LINE DEDENT output = s [ ind ] NEW_LINE break NEW_LINE DEDENT DEDENT return output NEW_LINE DEDENT S1 = " a " NEW_LINE S2 = " bc " NEW_LINE k = 4 NEW_LINE ans = KthCharacter ( S1 , S2 , k ) NEW_LINE print ( ans ) NEW_LINE