What is memoization vs tabulation in dynamic programming?
Answer
Both are DP techniques to avoid recomputing overlapping subproblems, but they approach it differently: Memoization (Top-Down): start with the original recursive solution; add a cache (hash map or array) to store computed results; before computing, check if the result is already cached; if yes, return cached; if no, compute, store, return. Pros: only computes needed subproblems (lazy); natural recursive structure; easy to implement from brute force. Cons: recursive call stack overhead; may hit stack overflow for large inputs; hash map overhead if using map. Tabulation (Bottom-Up): identify the order to compute subproblems (from smallest to largest); fill a table iteratively; each entry depends only on previously filled entries. Pros: no recursion (no stack overflow); typically faster (no call overhead); often allows space optimization (only need last few rows). Cons: must compute all subproblems even if not needed; requires understanding the order of computation. When to use each: memoization is easier to implement initially; tabulation is generally more efficient. Space optimization: in many DP problems, you only need the last row(s) — reduce O(n²) space to O(n) or O(1). Example: Fibonacci with memoization: cache[n] = f(n-1) + f(n-2); with tabulation: dp[i] = dp[i-1] + dp[i-2], iterate from 2 to n.
Previous
What is the coin change problem?
Next
What is the activity selection / interval scheduling problem?