optimize solution for problem 39