Insert a Character in a Rotated String | Function to insert the character ; To store last position where the insertion is done ; To store size of the string ; To store the modified string ; To store characters ; Add first character to the string ; Update the size ; Update the index of last insertion ; Insert all other characters to the string ; Take the character ; Take substring upto ind ; Take modulo value of k with the size of the string ; Check if we need to move to the start of the string ; If we don 't need to move to start of the string ; Take substring from upto temp ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; If we need to move to start of the string ; Take substring which will before the inserted character ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; Return the required character ; Driver Code ; Function call
def insert ( arr : list , n : int , k : int ) -> chr : NEW_LINE INDENT ind = 0 NEW_LINE sz = 0 NEW_LINE s = " " NEW_LINE ch = arr [ 0 ] NEW_LINE s += ch NEW_LINE sz = 1 NEW_LINE ind = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = arr [ i ] NEW_LINE s1 = s [ 0 : ind + 1 ] NEW_LINE temp = k % sz NEW_LINE ro = temp - min ( temp , sz - ind - 1 ) NEW_LINE if ro == 0 : NEW_LINE INDENT s2 = s [ ind + 1 : ind + 1 + temp ] NEW_LINE s3 = s [ ind + temp + 1 : sz ] NEW_LINE s = s1 + s2 + ch + s3 NEW_LINE ind = len ( s1 ) + len ( s2 ) NEW_LINE sz = len ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT s2 = s [ : ro ] NEW_LINE s3 = s [ ro : sz ] NEW_LINE s = s2 + ch + s3 NEW_LINE ind = len ( s2 ) NEW_LINE sz = len ( s ) NEW_LINE DEDENT DEDENT if ind == 0 : NEW_LINE INDENT return s [ sz - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return s [ ind - 1 ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ '1' , '2' , '3' , '4' , '5' ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( insert ( arr , n , k ) ) NEW_LINE DEDENT