Faster implementation for the problem 26