Dynamic Programming Foundations (1D)

Recognise overlapping subproblems, define states and transitions, and convert recursion to memoization and bottom-up tables for 1D problems.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Backtracking

Dynamic programming (DP) is recursion plus remembering. When a brute-force recursion solves the same subproblem many times and the problem has optimal substructure (the best answer is built from best answers to smaller parts), you can store results and cut exponential time to polynomial.

The four-step method

  • State: what does dp[i] mean in one precise sentence? For example "the maximum money robbed from houses 0..i".
  • Transition: how does dp[i] depend on smaller states? For House Robber, dp[i] = max(dp[i-1], dp[i-2] + a[i]).
  • Base cases: the smallest states answered directly.
  • Answer: which state (or max over states) is the final answer.

Top-down vs bottom-up

  • Memoization: write the recursion, cache results in an array or map. Easiest to derive from brute force.
  • Tabulation: fill a table in dependency order with loops. Avoids recursion depth issues and enables space optimisation: if dp[i] depends only on the last two states, keep two variables.

Start with memoization, then convert once it works.

Classic 1D problems

Climbing Stairs, House Robber (and the circular version), Min Cost Climbing Stairs, Decode Ways, Coin Change (min coins), Word Break, and Maximum Product Subarray.

Pitfalls

Vague state definitions (the number one cause of wrong DP), wrong iteration order in tabulation, and forgetting that "count ways" answers often need a modulus.

Key concepts

  • Overlapping subproblems
  • Optimal substructure
  • Defining state precisely
  • Memoization (top-down)
  • Tabulation (bottom-up)
  • Space optimisation
  • Counting vs optimisation DP

Mini project

For each of 8 problems write brute force, memoized and tabulated versions: Climbing Stairs, Min Cost Climbing Stairs, House Robber, House Robber II, Decode Ways, Coin Change, Word Break, and Maximum Product Subarray.

Check yourself

In Coin Change (minimum coins), what is the state, the transition, and why is greedy not enough?

Free resources