Wahed Invest interview question

How would I optimize my code solution