From Recursion to Dynamic Programming: A Problem-Solving Journey in Go

Introduction

Fibonacci gives a small example of repeated subproblems: first express the recurrence, then reuse computed results, then remove storage that the next step no longer needs. The Go implementations below make those time, stack and memory costs explicit.

Recursion: Elegant Problem-Solving, But Mind the Cost

Recursion is a technique where a function calls itself to solve smaller instances of the same problem until a base case is met. It's a natural way to express solutions for problems that can be defined in terms of smaller subproblems. For example, if we want to compute the nth Fibonacci number, a recursive approach mirrors the mathematical definition:

Fibonacci definition: F(0) = 0, F(1) = 1, and for n ≥ 2, F(n) = F(n-1) + F(n-2).

A straightforward Go implementation of this definition is concise:

// Naive recursive Fibonacci in Go
func fibRecursive(n int) int {
    if n < 2 {
        return n  // base cases: fib(0)=0, fib(1)=1
    }
    return fibRecursive(n-1) + fibRecursive(n-2)  // recursive step
}

This recursive function is easy to read and clearly reflects the problem definition. If you call fibRecursive(5), it will correctly return 5, and so on. However, there's a hidden cost here: redundant calculations. To illustrate, let's examine what happens when computing fibRecursive(5):

  • fibRecursive(5) calls fibRecursive(4) and fibRecursive(3).
  • fibRecursive(4) calls fibRecursive(3) and fibRecursive(2).
  • Notice fibRecursive(3) is now called twice (overlap)! Similarly, fibRecursive(2) will be called multiple times in those branches.

For small n this isn't a big issue, but as n grows, the number of function calls explodes. The naive recursion ends up recalculating the same Fibonacci values over and over. The call count satisfies C(n) = 1 + C(n-1) + C(n-2) with C(0) = C(1) = 1, so C(n) = 2F(n+1) - 1. This is Θ(φⁿ), where φ is the golden ratio; O(2ⁿ) is a valid but loose upper bound. For n=50 that is 40,730,022,147 calls, not 2⁵⁰ calls. The recursion also needs O(n) stack depth.

All int examples here require n >= 0 and values small enough to fit in the platform's int: F(46) is the last fitting value on signed 32-bit systems, and F(92) on signed 64-bit systems. The memoized function also expects a non-nil map. Memoization changes the work performed, not the numeric range.

Dynamic Programming: Recursion with Memory (Memoization)

After observing the inefficiency of the pure recursive approach, a seasoned developer's mind will look for ways to avoid repeated work. This is where dynamic programming (DP) comes in. At its heart, dynamic programming solves problems by breaking them into subproblems and storing the results of those subproblems so they don't have to be recomputed. Top-down memoization is one form of DP; bottom-up tabulation computes the same states in dependency order without recursion. The technique of storing results is often called memoization.

Definition: Dynamic programming is an approach to solving complex problems by splitting them into simpler subproblems and solving each subproblem only once, saving its solution for reuse. This avoids repetitive calculations and greatly improves efficiency.

How does this apply to our Fibonacci problem? The key observation is that, say, once we compute fib(3), we should remember it. The next time we need fib(3) (and in the naive recursion we needed it multiple times), we can return the remembered value instantly instead of computing it again. By doing so for all intermediate results, we ensure each Fibonacci number is computed only one time. This optimization reduces the time complexity from exponential to linear O(n), which is a drastic improvement.

To implement this, we can use a simple cache (in Go, a map works well) to store computed results. This technique, memoization, means before computing a Fibonacci number, we check if we've already computed it. Here's how we can code the memoized version in Go:

// Optimized Fibonacci using DP (memoization) in Go
func fib(n int, memo map[int]int) int {
    // If we have seen n before, return the cached result
    if val, found := memo[n]; found {
        return val
    }
    // Base cases: 0 or 1
    if n < 2 {
        memo[n] = n
        return n
    }
    // Recursive computation with memoization
    result := fib(n-1, memo) + fib(n-2, memo)
    memo[n] = result  // store the computed result for n
    return result
}

// Example usage:
func main() {
    cache := make(map[int]int)
    fmt.Println(fib(7, cache))  // prints 13, i.e., Fibonacci(7)
}

What's happening here? We introduced a map memo to cache results. The function fib(n, memo) works as follows:

  1. Check the cache: If n is already in memo, we immediately return memo[n]. (No need to recompute!)
  2. Handle base cases: If n < 2, we record the base value (0 or 1) in the map and return it.
  3. Recurse with caching: If we don't have the answer and n is not a base case, we recursively compute fib(n-1) and fib(n-2), then add them. Before returning, we save memo[n] = result so that any future calls for fib(n) will retrieve the result from memory.

Each state is computed once, giving O(n) arithmetic operations and O(n) map storage plus O(n) recursion depth, assuming fixed-width arithmetic. No timing result is claimed here; actual runtime depends on the machine and implementation.

Bottom-up, then constant extra space

Fibonacci only depends on the previous two values. A table is unnecessary if the caller needs just F(n):

func fibIterative(n int) int {
    if n < 2 {
        return n
    }
    previous, current := 0, 1
    for i := 2; i <= n; i++ {
        previous, current = current, previous+current
    }
    return current
}

The loop starts each iteration with F(i-2) and F(i-1), then advances to F(i-1) and F(i). It uses O(n) additions and O(1) extra fixed-width storage, with no recursive stack. Keeping the n<=92 bound on a 64-bit target matters: the algorithm avoids computing F(n+1) merely to return F(n).

Thought Process

At this point, it's worth reflecting on how one arrives here. When I first approach a problem like Fibonacci, I might implement the straightforward recursive solution and test it on small inputs. Seeing it work for, say, n=5 or n=10, I might then try a larger input (like n=40) and notice it slows to a crawl. That slowdown is a red flag that prompts me to think, "Why is this so slow? Am I doing repeated work?" Visualizing or tracing the recursion, I realize many sub-calls compute the same values. The natural next thought is, "Can I store results to avoid repeating myself?" This leads directly to the idea of maintaining a cache (memoization). By iterating and refining the approach in this way, I transform a brute-force solution into a much more efficient one. This problem-solving pattern – identify inefficiency, then optimize by eliminating redundancy – is at the core of many algorithmic improvements.

Beyond Fibonacci: Why This Matters

The Fibonacci example is a classic teaching tool, but the lessons here scale to far more complex challenges. Dynamic programming is a cornerstone technique in computer science, used to solve a variety of real-world problems. Once you learn to recognize overlapping subproblems and optimal substructures, you can apply DP to path-finding algorithms, optimization puzzles, scheduling problems, and more. For instance, classic challenges like the Knapsack problem or computing shortest paths (e.g., the Floyd-Warshall algorithm) are textbook applications of dynamic programming. The useful skill is identifying which state determines a subproblem and which computed states must remain available.

Checking the implementations

Compare all three functions against known values such as F(0)=0, F(1)=1, F(7)=13 and F(20)=6765. Cross-checking implementations helps, but the expected values should not come only from another version of the same code. For performance comparisons, use Go benchmarks with a bounded input and a fresh memo map for each cold run; a warm cache measures a different operation.

The recurrence stays the same through all three implementations. What changes is whether repeated states are recomputed, cached, or discarded once their successors no longer need them.