Google interview question

How would you optimize this solution