Solve a medium-difficulty array manipulation problem and optimize it from O(N^2) to O(N) time complexity.