recursive solution without explicity pops and pushes