POST 1 of 5 MorningDSAConcept
DP is recursion + memoisation
Dynamic programming has a reputation as the hardest topic in interviews. Most of that reputation is undeserved. DP isn't a separate algorithm; it's a recipe. A problem is solvable by DP if it has two properties: Optimal substructure. The optimal answer to size n depends on optimal answers to smaller sizes. (If you know fib(n-1) and fib(n-2), you know fib(n).) Overlapping subproblems. The same smaller problems get computed multiple times across the recursion tree. (fib(n-3) shows up under both fib(n-1) and fib(n-2).) When both properties hold, cache the smaller answers. That's DP. Recursion + memoisation. The naive recursion has exponential runtime because of the recomputation. The memoised version has linear (or polynomial) runtime because each subproblem is solved exactly once. Classical DP problems and the state shape: Fibonacci — dp[n] = answer for size n. 1D state. Climbing stairs (count distinct paths) — dp[n] = ways to reach step n. 1D. Coin change (min coins for amount) — dp[a] = min coins for amount a. 1D. Longest common subsequence — dp[i][j] = LCS of first i chars of A and first j chars of B. 2D. Edit distance — dp[i][j] = edits to transform first i chars of A into first j chars of B. 2D. Knapsack (maximise value within weight limit) — dp[i][w] = max value using first i items with weight budget w. 2D. The state shape (1D, 2D, etc.) usually drops out of the problem statement. Identify what the smaller problem depends on. If just one parameter — 1D. If two — 2D. DP is pattern recognition plus careful state design. The patterns repeat; once you've coded ten DP problems, the eleventh is recognisable.
#DSA#Algorithms#Python#100DaysOfCode#CodingInterview#DynamicProgramming