Walk through your approach to solving a classic array manipulation problem, and explain how you would optimize its time and space complexity.