Enhanced solution with O(n) running time and O(1) space