Solve a medium-difficulty array manipulation problem without using external libraries, focusing on optimal time and space complexity.