Refactor the code using constant space.