Difference Between Recursion and Iteration

In data structures and algorithms, iteration and recursion are two fundamental problem-solving approaches. Both execute instructions repeatedly until the task is completed. But there are significant differences between recursion and iteration in terms of thought processes, implementation approaches, analysis techniques, code complexity and performance.

Difference in terms of thought process

Sometimes, a coding problem can be solved using both iteration and recursion, but the choice of approach depends on the nature of the problem and which one is more intuitive to use.

  • For example, recursion is more natural for algorithms like binary search, merge sort, quick sort, DFS traversal of a graph, etc. Similarly, approaches like backtracking and data structures like trees are easier to understand using recursion.
  • On the other hand, many coding problems are easy to solve using iteration. Recursive solution can be challenging or impossible to understand in these cases. For example: insertion sort, heap sort and BFS traversal of a graph or tree are efficiently implemented using iteration.

Popular recursive and iterative problem solving approaches in DSA

Difference in terms of implementation approach

Iteration is implemented using a loop, which consists of initialisation, increment of loop variables, code inside the loop body and termination conditions. In contrast, recursion is implemented using function calls and defined in terms of the number of sub-problems, input size of sub-problems, base cases and extra operations required to combine solutions to the sub-problems.

  • In a recursive implementation, the compiler uses the call stack to store information about each function call, such as its input values and where execution should resume. This lets the program keep track of the current state while solving smaller subproblems.
  • It is possible to transform every recursive implementation into an iterative implementation using a stack (which is what the compiler does in the background).
  • In most cases, iterative implementation using a stack becomes more complex due to several input parameters, extra operations and complex nature of recursive calls. So changing a recursive algorithm to an iterative algorithm can make the code more complicated or less maintainable.
  • There are some situations where recursion is simple and can be easily converted into iterative code using a stack. One idea that works well is to mimic what the compiler does. An excellent example of this is iterative DFS traversal using a stack.
  • There are some recursive solutions that can be implemented iteratively without using a stack. Classic examples of this is finding nth Fibonacci, finding the factorial, binary search, etc.

Difference in terms of code execution

Iterative code repeatedly executes statements in a loop until the problem is solved. In contrast, recursive code solves a problem using smaller subproblems until it reaches a base case.

  • Recursion can be slower than iteration because each function call adds overhead and uses space on the call stack. But it can make problems easier to express when they naturally break down into smaller subproblems.
  • Iteration often runs faster because it avoids repeated function-call overhead. But for some problems, an iterative solution can be harder to write and understand.

Difference in terms of code error

  • In iteration, an infinite loop can occur due to an error in the assignment or increment of the loop variable or a wrong terminating condition. This can consume system resources like processor time or memory and stop the program execution.
  • In recursion, an infinite recursion may occur due to the absence of base cases or incorrect base cases. This can cause a stack overflow scenario.

Both iteration and recursion can be prone to small but critical mistakes, such as an “off-by-one” error in iteration or passing the wrong value to a function parameter in recursion. It is important to test the conditions and variables involved in these approaches to avoid such errors.

Difference in terms of code analysis

  • In general, analysing iterative code is relatively simple. We count the number of loop iterations and multiply it by the time complexity of the code executed in each iteration. But there are exceptions where counting iterations can be tricky or where loop operations take less time than expected.
  • The primary method for analysing recursive code is the recursion tree method. We draw the recursion tree, assign a cost to each node and sum the costs at each level. This can be difficult for complex recurrence relations. But divide-and-conquer algorithms can be analysed easily using the Master Theorem.

Comparing recursion vs iteration using code examples

Here are some examples of recursive and iterative solutions to the same problem, along with a comparison of their thought process, performance and code simplicity.

Example 1: Finding the factorial of a number

Finding the nth factorial can be implemented using either an iterative or a recursive approach. Although the recursive solution may look simpler, it can be slower because of function-call overhead and requires extra space for the call stack.

Both approaches have a time complexity of O(n), but the recursive solution requires O(n) extra space for the call stack. This space requirement can be an important factor when choosing between them.

Recursive pseudocode

factorial(n)
    if n == 0
        return 1

    return n * factorial(n - 1)

Iterative pseudocode

factorial(n)
    result = 1

    for i from 2 to n
        result = result * i

    return result

Example 2: Finding nth Fibonacci

The recursive solution for calculating Fibonacci numbers is simple and easy to understand, but it is highly inefficient, with time complexity of O(2^n) and space complexity of O(n). In contrast, the iterative solution has a time complexity of O(n) and a space complexity of O(1), which makes it much more efficient.

When choosing between iterative and recursive solutions, we need to consider the trade-offs among simplicity, time complexity, and space complexity.

Recursive pseudocode

fib(n)
    if n <= 1
        return n

    return fib(n - 1) + fib(n - 2)

Iterative pseudocode

fibonacci(n)
    if n <= 1
        return n

    previousFibonacci = 0
    currentFibonacci = 1

    for index from 2 to n
        nextFibonacci = previousFibonacci + currentFibonacci
        previousFibonacci = currentFibonacci
        currentFibonacci = nextFibonacci

    return currentFibonacci

Example 3: Binary search

In this case, both the iterative and recursive binary search solutions look simple, but the recursive solution can be easier to understand. Despite this, the iterative solution is more efficient in terms of time and space complexity. Both solutions have a time complexity of O(log n), but the recursive solution requires O(log n) extra space for the call stack. In contrast, the iterative solution has no recursive-call overhead and requires only O(1) space, which makes it more efficient.

Recursive pseudocode

binarySearch(X, l, r, key)
    if l > r
        return -1

    mid = l + (r - l) / 2

    if X[mid] == key
        return mid
    else if X[mid] > key
        return binarySearch(X, l, mid - 1, key)
    else
        return binarySearch(X, mid + 1, r, key)

Iterative pseudocode

binarySearch(X, l, r, key)
    while l <= r
        mid = l + (r - l) / 2

        if X[mid] == key
            return mid
        else if X[mid] < key
            l = mid + 1
        else
            r = mid - 1

    return -1

Example 4: Insertion sort

In this case, both iterative and recursive solutions have a time complexity of O(n²). But the iterative solution is more efficient in terms of space complexity. The recursive solution requires O(n) extra space for the call stack, while the iterative solution has no recursive-call overhead and requires only O(1) space.

Iterative pseudocode

insertionSort(X, n)
    for i from 1 to n - 1
        currentValue = X[i]
        j = i - 1

        while j >= 0 and X[j] > currentValue
            X[j + 1] = X[j]
            j = j - 1

        X[j + 1] = currentValue

Recursive pseudocode

insertionSort(X, n)
    if n <= 1
        return

    insertionSort(X, n - 1)
    currentValue = X[n - 1]
    i = n - 2

    while i >= 0 and X[i] > currentValue
        X[i + 1] = X[i]
        i = i - 1

    X[i + 1] = currentValue

Example 5: Pre-order tree traversal

Here, recursive code is simple and easy to understand because it involves only one function parameter and a few lines of code. On the other hand, we can also easily implement preorder traversal iteratively using a stack. In the worst case, both recursive and iterative approaches have O(n) space and time complexity.

Recursive pseudocode

preorder(root)
    if root is null
        return

    process(root.data)
    preorder(root.left)
    preorder(root.right)

Iterative pseudocode

iterativePreorder(root)
    if root is null
        return

    treeStack = empty stack
    currNode = root
    prevNode = null

    while treeStack is not empty or currNode is not null
        if currNode is not null
            process currNode.data
            treeStack.push(currNode)
            currNode = currNode.left
        else
            prevNode = treeStack.pop()
            currNode = prevNode.right

Critical ideas to think!

  1. Despite being slower in general, why do some people prefer recursion over iteration?
  2. Is there a general guideline for converting recursive code into iterative code?
  3. Is it possible to convert all recursive code into iterative code or vice versa?

Enjoy learning, Enjoy algorithms!

More from EnjoyAlgorithms

Self-paced Courses and Blogs