Improved solution as suggested