Optimizations on problem 2