Better version in O(n) time and O(1) space