Solve a medium-difficulty array manipulation problem, focusing on optimizing space and time complexity.