Explain the space complexity of the recursive solution you just wrote, and refactor it iteratively to save memory.