Code is showing TLE

Hey, could you please help me optimize my code;
my code:https://onlinegdb.com/yUDf1RB0F

Hi Adarsh,
u can refer this --> https://ide.codingblocks.com/s/620452

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

could you please explain the logic with the flag?

basically we use flag to avoid repetitions
for example if input is AAA
it would print only once AAA, instead of multiple repetitions of the same.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.