Solve a classic array or string manipulation problem, focusing on optimizing both time and space complexity.