improved to yield space complexity of O(1)