A2Z Lesson

Log in
← Back to the A2Z sheet

Step 17 Dynamic Programming — Introduction

Introduction to DP

Easy

Dynamic programming (DP) is recursion with a memory: when a problem breaks into subproblems that repeat, solve each distinct subproblem once, store its answer, and reuse it. That single change routinely converts exponential brute force into polynomial time — Fibonacci goes from O(2^n) to O(n). This lesson gives you the recognition test for DP, the five-step recipe, and the three implementation styles (memoization, tabulation, space-optimised) on one running example.

When DP applies: the two properties

A problem is DP-shaped when it has (1) overlapping subproblems — the recursion tree revisits the same smaller problems many times — and (2) optimal substructure — an optimal answer is assembled from optimal answers of those subproblems (true for counting and min/max problems where choices decompose cleanly).

Contrast with divide and conquer (merge sort): its subproblems are disjoint, so there is nothing to reuse and DP adds nothing. Contrast with greedy: greedy commits to one locally best choice and never revisits it; DP systematically considers choices but caches their results. If you can draw the recursion tree and see repeated nodes, DP will help.

The Fibonacci story: from exponential to linear

Naive fib(n) = fib(n-1) + fib(n-2) recomputes fib(n-2) twice, fib(n-3) three times, and so on — the call tree has O(2^n) nodes even though there are only n+1 distinct subproblems (fib(0) .. fib(n)).

Memoization (top-down): keep a cache; before computing, check it; after computing, store. Each distinct subproblem is now solved once: O(n) time, O(n) space for cache plus recursion stack. Tabulation (bottom-up): fill a table from the base cases upward in dependency order — fib[0], fib[1], then each fib[i] = fib[i-1] + fib[i-2]. Same O(n) time, no recursion. Space optimisation: since fib[i] depends only on the previous two values, keep two variables instead of the table — O(1) space. Recognising what a state actually depends on is how most DP solutions shed their table at the end.

# top-down (memoization) from functools import lru_cache @lru_cache(maxsize=None) def fib_memo(n): if n <= 1: return n return fib_memo(n - 1) + fib_memo(n - 2) # bottom-up (tabulation) def fib_tab(n): if n <= 1: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] # space-optimised def fib_opt(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a

The five-step recipe

Every DP in this module can be produced mechanically:

1. Define the state: what does dp[...] mean, in one sentence? ('dp[i] = maximum sum obtainable considering the first i elements.') The state variables are the things that change across subproblems — an index, a capacity, a previous choice. 2. Write the recurrence: express dp[state] using smaller states, mirroring the choices at each step (take / skip, come from up / left, etc. 3. Fix the base cases: the smallest states answered directly. 4. Choose the computation order so every dependency is ready (for tabulation) — usually increasing index; for 2D, by rows. 5. Locate the answer: which state is the final result? (Not always dp[n] — sometimes a max over a row.)

If you cannot state step 1 in one sentence, the state is wrong or missing a dimension — that is the signal to add the missing variable (for example, 'previous element taken or not' in house-robber style problems).

Second example: climbing stairs

Problem: count ways to reach step n taking 1 or 2 steps at a time. State: ways(i) = number of ways to reach step i. Recurrence: the last move was a single step from i-1 or a double from i-2, so ways(i) = ways(i-1) + ways(i-2). Base: ways(0) = 1 (already there), ways(1) = 1. Answer: ways(n). This is Fibonacci wearing a costume — and that recognition skill (this new problem is that solved problem) is most of what 'being good at DP' means in practice.

Complexity formula for any DP: (number of distinct states) x (cost per state transition). Here n states x O(1) transition = O(n). Quote complexities this way in interviews and use it to sanity-check whether your state design is feasible.

Common mistakes

(1) A state definition that secretly depends on history not captured in the state — answers then differ for the 'same' state and caching is wrong. (2) Base cases off by one, especially dp[0]: decide whether it means 'empty input' and be consistent. (3) In tabulation, iterating in an order where dependencies are not yet computed (for example, knapsack's 0/1 items require iterating capacity backwards — iterating forwards silently reuses the same item twice and solves the unbounded variant). (4) Forgetting the required modulo (usually 10^9 + 7) on counting problems. (5) Deep recursion in top-down solutions hitting recursion limits on large n — switch to tabulation or raise the limit deliberately.

Key points

  • DP = recursion + caching, applicable when subproblems overlap and optimal answers compose from optimal sub-answers.
  • Memoization is top-down with a cache; tabulation is bottom-up in dependency order; both are O(states x transition).
  • The five steps: define state in one sentence, recurrence, base cases, order, locate the answer.
  • If the same subproblem can be reached with different histories that matter, your state is missing a variable.
  • Space optimisation: keep only the previous row / last few values the recurrence actually reads.

Suggested questions

Climbing stairs ↗ The Fibonacci-shaped counting DP from this lesson — your first state-and-recurrence drill.
Frog Jump ↗ Min-cost DP on an index state; practise writing the recurrence from the last jump backwards.
Maximum sum of non adjacent elements ↗ The take / skip choice pattern that recurs across half the module.
Grid unique paths ↗ Your first 2D state: dp[i][j] from dp[i-1][j] and dp[i][j-1].

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.