Fixed space complexity && Refactoring