Optimized code for problem 1