It was posted in the wrong forum and I have moved it to the correct forum.

Regarding your problem there is a standard algo for such a solution to the problem. will help you get the idea about the algo.

Originally Posted by rai_gandalf
Also, if possible, tell me is there any way to code it non-recursively.
If not all almost every recursive problem has a non recursive solution specially standard algos.