Improved solution for #6.