Solution to Problem 45, need to find a better solution time complexity wise