refactored recusrive solution