Solve a classic array-manipulation problem and explain how you would optimize your solution from O(n^2) to O(n) time complexity.