How can code be made more efficient

How can the code for this problem be made more efficient

Hi @kartikstackexchange_77770317975ae8b4
U can refer this

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.