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
function Insert ( arr , n , k ) { let ind = 0 ; let sz = 0 ; let s = " " ; let ch = arr [ 0 ] ; s += ch ; sz = 1 ; ind = 0 ; for ( let i = 1 ; i < n ; i ++ ) { ch = arr [ i ] ; let s1 = s . substring ( 0 , ind + 1 ) ; let temp = k % sz ; let ro = temp - Math . min ( temp , sz - ind - 1 ) ; if ( ro == 0 ) { let s2 = s . substring ( ind + 1 , ind + 1 + temp ) ; let s3 = s . substring ( ind + temp + 1 , sz ) ; s = s1 + s2 + ch + s3 ; ind = s1 . length + s2 . length ; sz = s . length ; } else { let s2 = s . substring ( 0 , ro ) ; let s3 = s . substring ( ro , sz ) ; s = s2 + ch + s3 ; ind = s2 . length ; sz = s . length ; } } if ( ind == 0 ) { return s [ sz - 1 ] ; } else { return s [ ind - 1 ] ; } } let arr = [ ' ' , ' ' , ' ' , ' ' , ' ' ] ; let k = 2 ; let n = arr . length ; document . write ( Insert ( arr , n , k ) ) ;