Solve a medium-level array manipulation problem, focusing on optimizing time complexity while keeping space usage minimal.