Faster algorithm for problem 229