MANYCHEF TLE

i’m gettting tle for this problem, and also i have a doubt why should the checking and replacing be done from the end of the string (mentioned in editorial ),btw i did it from the starting of the string

question link

my submission