Optimized solution to question 18.