Write a function to solve a classic array manipulation problem with optimal time and space complexity.