Amazon Interview Question

Question based on recursion, but there is also non recursive way to solve the problem