Insert a Character in a Rotated String | Java implementation of the approach ; 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
import java . util . * ; class GFG { public static char Insert ( char arr [ ] , int n , int k ) { int ind = 0 ; int sz = 0 ; String s = " " ; char ch = arr [ 0 ] ; s += ch ; sz = 1 ; ind = 0 ; for ( int i = 1 ; i < n ; i ++ ) { ch = arr [ i ] ; String s1 = s . substring ( 0 , ind + 1 ) ; int temp = k % sz ; int ro = temp - Math . min ( temp , sz - ind - 1 ) ; if ( ro == 0 ) { String s2 = s . substring ( ind + 1 , ind + 1 + temp ) ; String s3 = s . substring ( ind + temp + 1 , sz ) ; s = s1 + s2 + ch + s3 ; ind = s1 . length ( ) + s2 . length ( ) ; sz = s . length ( ) ; } else { String s2 = s . substring ( 0 , ro ) ; String s3 = s . substring ( ro , sz ) ; s = s2 + ch + s3 ; ind = s2 . length ( ) ; sz = s . length ( ) ; } } if ( ind == 0 ) { return s . charAt ( sz - 1 ) ; } else { return s . charAt ( ind - 1 ) ; } } public static void main ( String [ ] args ) { char arr [ ] = { '1' , '2' , '3' , '4' , '5' } ; int k = 2 ; int n = arr . length ; System . out . println ( Insert ( arr , n , k ) ) ; } }