Converted recursive algorithm to iterative