Memoization vs Tabulation: Top-Down vs Bottom-Up Dynamic Programming
Overview Both techniques avoid redundant recomputation in dynamic programming problems by caching subproblem results, but they build that cache in opposite directions. Memoization starts from the original problem and recurses downward, caching results lazily as calls return, while tabulation starts from the base cases and iterates upward, filling a table until the final answer is reached. Comparison Diagram Memoization (Top-Down)fib(4)fib(3)fib(2)*fib(2)fib(1)* = cache hit, no recomputememo cachefib(0)=0 fib(1)=1fib(2)=1 fib(3)=2fib(4)=3recurse down, cache on returnTabulation (Bottom-Up)for i = 0 .. ndp[0]0dp[1]1dp[2]1dp[3]2dp[4]3final answerbuild up from base cases Comparison Table Aspect Memoization (Top-Down) Tabulation (Bottom-Up) Entry point Starts from the original problem call, e.g. solve(n) Starts from the smallest base cases, e.g. dp[0], dp[1] Control flow Recursive function calls, following the natural recurrence Iterative loop over subproblem indices in dependency order Subproblems computed Only those actually reachable from the initial call All subproblems up to the target, whether needed or not Storage structure Hash map or sparse cache keyed by call arguments Array or table indexed by subproblem parameters Order dependency Implicit, resolved automatically by call stack ordering Explicit, programmer must sort iteration to respect dependencies Call overhead Function call and stack frame cost per subproblem No function call overhead, just array reads and writes Stack risk Can hit recursion depth limits or stack overflow on deep inputs No recursion, so no stack depth concerns Code shape Mirrors the recursive definition, often easier to derive first Requires reformulating the recurrence as an explicit loop Key Differences Memoization computes subproblems on demand, while tabulation computes every subproblem exhaustively in order. Memoization relies on the call stack to sequence work; tabulation relies on a manually ordered loop. Tabulation typically enables space optimization (e.g. keeping only the last few rows) since access order is known upfront. Memoization can be stack-limited on deep recursion, whereas tabulation avoids recursion entirely. Memoization is usually a smaller code change from a naive recursive solution; tabulation requires restructuring it as iteration. When to Use Each Memoization (Top-Down) ...