Memoization keeps the natural recursive structure and adds a cache: before computing, check whether the answer is stored; after computing, store it. For Fibonacci this turns an exponential algorithm into a linear one. The cache is typically an array indexed by the subproblem parameters and initialized to a sentinel such as 0 or -1.
Remember
long long fib(int n) {
if (n < 2) return n;
if (memo[n]) return memo[n]; /* cache hit */
long long a = fib(n - 1), b = fib(n - 2);
return memo[n] = a + b; /* cache fill */
}
Reference
Cheat Sheet
Keep these facts handy while you work with Memoization in C in C.
#include <stdio.h>
static long long memo[31];
static long calls_memo, calls_naive;
static long long fib_memo(int n) {
calls_memo++;
if (n < 2) return n;
if (memo[n]) return memo[n];
long long a = fib_memo(n - 1);
long long b = fib_memo(n - 2);
return memo[n] = a + b;
}
static long long fib_naive(int n) {
calls_naive++;
if (n < 2) return n;
return fib_naive(n - 1) + fib_naive(n - 2);
}
int main(void) {
long long m = fib_memo(30);
printf("memoized fib(30) = %lld (%ld calls)\n", m, calls_memo);
long long v = fib_naive(30);
printf("naive fib(30) = %lld (%ld calls)\n", v, calls_naive);
return 0;
}
The memoized version makes 2n - 1 = 59 calls: each value is computed once and reused.
The naive version recomputes the same values millions of times.
Both produce 832040; only the amount of work differs.
Edge Cases & Pitfalls
Check these before relying on Memoization in C in real programs.
sentinel
Sentinel collisions
If 0 can be a valid answer, use -1 as "not computed".
depth
Recursion depth
Memoization is still recursive; very deep recursion can overflow the stack.
Remember
Key Takeaways
Recursion plus cache.
Compute each state once.
Pick a safe sentinel.
One line: Memoization keeps the natural recursive structure and adds a cache: before computing, check whether the answer is stored; after computing, store it.
Frequently Asked Questions
Storing the results of expensive function calls so repeated calls with the same input return the cached value.
It is a specific form of caching used in recursion to avoid repeated subproblems.
Continue with "Tabulation (Bottom-Up DP) in C" next. Fill a table iteratively from base cases; minimum coin change example. The C Algorithm Techniques hub lists every topic in order.