Skip to content
Back to posts

Converting Recursion to Iteration

A step-by-step look at replacing recursion with accumulators or explicit stacks in several representative algorithms.

Recursive code is often concise, but every call consumes stack space. There are two common ways to convert it to iteration.

For tail-recursive functions, move intermediate state into accumulator parameters. Factorial, for example, can carry the current product and repeatedly update it in a loop:

def factorial(n):
result = 1
while n > 1:
result *= n
n -= 1
return result

General recursion requires preserving work that would otherwise live in call frames. Use an explicit stack, push the pending subproblems, and pop them until none remain. An iterative quicksort can store (left, right) ranges, partition one range, then push the two remaining ranges.

The key is to identify what each recursive frame remembers: arguments, local state, and what must happen after a child call returns. Tail calls need only updated state; non-tail calls need an explicit representation of the continuation. Iteration avoids call-stack limits, although an explicit stack may still use comparable memory.


Originally published on SegmentFault.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.