Refactored algorithm