Improved solution for Q5