recursive solution improved