Dynamic Programming

In short: Dynamic programming (DP) is a way to solve a problem by breaking it into overlapping subproblems, solving each subproblem once, and storing the results so they're reused instead of recomputed. It works when a problem has overlapping subproblems and optimal substructure, and it's written either top-down (recursion plus memoization) or bottom-up (filling in a table).

Quick reference

Dynamic programming (DP) is a way to solve a problem by breaking it into smaller overlapping subproblems, solving each subproblem only once, and storing its answer so it can be reused instead of recomputed. The stored answers are then combined into the answer to the original problem.

When to use it:

  • The problem has overlapping subproblems: a brute-force recursive solution would solve the same smaller problem again and again.
  • The problem has optimal substructure: the best answer can be built from the best answers to its subproblems.
  • It asks you to count the ways to do something, find a minimum or maximum, or decide whether something is possible, over a series of choices.

Two ways to write it:

  • Top-down (memoization): write the recursive solution, then save each subproblem's answer the first time you compute it.
  • Bottom-up (tabulation): fill in a table of answers with a loop, starting from the smallest subproblems.

Why bother:

  • It turns many exponential-time brute-force solutions into polynomial-time ones. A DP solution's running time is usually (number of distinct subproblems) × (work per subproblem).

The name has little to do with programming in the coding sense. Mathematician Richard Bellman coined it in the 1950s, when "programming" meant planning: finding the best schedule or plan.

The Two Properties of a Dynamic Programming Problem

Dynamic programming works on problems that have both of these:

  1. Overlapping subproblems. Breaking the problem down produces the same smaller problems over and over. A plain recursive Fibonacci method, for example, computes fib(2) three separate times on its way to fib(5). Saving each answer the first time means you never redo that work.

  2. Optimal substructure. An optimal answer to the problem can be built from optimal answers to its subproblems. Shortest paths have this property: if the shortest route from A to C passes through B, then its A-to-B part must be a shortest route from A to B (otherwise you could swap in the shorter one and get a shorter route to C).

If the subproblems don't overlap—like the two halves in merge sort, which never share any work—there's nothing to reuse, and plain recursion (divide and conquer) is enough. And if a problem lacks optimal substructure, combining the best answers to its subproblems won't give you the best overall answer. The classic example is the longest simple path (no repeated nodes) in a graph: the longest path from A to C through B isn't necessarily a longest path from A to B followed by a longest path from B to C, since those two paths could share nodes.

Strictly speaking, "optimal substructure" is about optimization problems (find the minimum or maximum). For counting problems ("how many ways are there to...?"), the equivalent requirement is that you can write the answer as a formula over the answers to smaller subproblems: a recurrence.

How to spot a DP problem in a coding interview

  • It asks for the number of ways to do something, the minimum or maximum cost, value, or length, or whether a target can be reached at all.
  • The brute-force solution tries every combination of choices, and its tree of recursive calls has repeated calls with the same arguments.
  • Each choice leaves you with a smaller version of the same problem: a shorter prefix of a string, a smaller amount of money, fewer items, or less space in a bag.

Example: Climbing Stairs, Top-Down and Bottom-Up

Problem: you're climbing a staircase with n steps. Each move, you climb either 1 step or 2 steps. How many different ways can you get to the top?

For a staircase with 3 steps there are 3 ways: 1+1+1, 1+2, and 2+1.

Step 1: Find the recurrence

Think about your last move. Either you took 1 step from step n - 1, or you took 2 steps from step n - 2. So the number of ways to reach step n is the number of ways to reach step n - 1 plus the number of ways to reach step n - 2:

ways(n) = ways(n - 1) + ways(n - 2)

The base cases are ways(0) = 1 (you're already at the top, and doing nothing counts as one way) and ways(1) = 1.

Step 2: Write it recursively (correct, but slow)

public static long countWays(int n) { // base cases: there's one way to climb 0 steps (do nothing) // and one way to climb 1 step if (n <= 1) { return 1; } // the last move was either 1 step (from n - 1) or 2 steps (from n - 2) return countWays(n - 1) + countWays(n - 2); }

This works, but it takes exponential time, roughly O(2^n). The calls branch into a tree where the same subproblems show up again and again: computing ways(5) computes ways(3) twice and ways(2) three times. Those are overlapping subproblems, so dynamic programming can help.

Step 3: Top-down, with memoization

Keep the recursion, but save each answer the first time you compute it (that's memoization). Before doing any work, check whether the answer is already saved:

import java.util.HashMap; import java.util.Map; public static long countWays(int n) { return countWays(n, new HashMap<>()); } private static long countWays(int n, Map<Integer, Long> memo) { if (n <= 1) { return 1; } // already solved this subproblem? reuse the saved answer. if (memo.containsKey(n)) { return memo.get(n); } long result = countWays(n - 1, memo) + countWays(n - 2, memo); memo.put(n, result); return result; }

Now each subproblem, ways(0) through ways(n), is computed only once, so this runs in O(n) time and takes O(n) space for the memo and the call stack. For a 30-step staircase, the plain recursive version runs its recursive method 2,692,537 times. The memoized version runs it 59 times.

Step 4: Bottom-up, with tabulation

Instead of starting at n and recursing down, start at the base cases and fill in a table going up (that's going bottom-up). Each entry only needs the two entries before it, and those are already filled in:

public static long countWays(int n) { // ways[i] is the number of ways to climb i steps long[] ways = new long[n + 1]; // base cases ways[0] = 1; if (n >= 1) { ways[1] = 1; } // fill in the table from the smallest subproblem up for (int i = 2; i <= n; i++) { ways[i] = ways[i - 1] + ways[i - 2]; } return ways[n]; }

Here's the table it builds for a 5-step staircase:

Steps (i) 0 1 2 3 4 5
Ways to climb i steps 1 1 2 3 5 8

So there are 8 ways to climb 5 steps. This version also takes O(n) time, but there's no recursion, so a big n can't cause a stack overflow. And since each entry only depends on the two before it, you could keep just those two values instead of the whole table, bringing the space down to O(1).

Those numbers might look familiar: ways(n) equals fib(n + 1), where fib is the Fibonacci series starting from fib(0) = 0 and fib(1) = 1. To practice taking a recursive solution all the way to an efficient one, try computing the nth Fibonacci number.

Top-down vs. bottom-up: which should you use?

Top-down (memoization) Bottom-up (tabulation)
Written as Recursion plus a cache (often a hash map) Loops that fill in a table (usually an array)
Solves Only the subproblems the recursion actually reaches Every subproblem in the table, in order
Call stack Grows with the recursion depth, so very large inputs can overflow it No recursion, so no stack overflow
Saving space Harder, since the cache holds every subproblem it solved Often easy: keep only the entries or rows you still need
Easiest when The recursive solution is natural and the order to solve subproblems in isn't obvious You can see an order where each subproblem's dependencies come first

For most problems, both have the same time complexity. In an interview, a reliable path is to write the brute-force recursion, add memoization, and then (if there's time, or if the interviewer asks about space) convert to bottom-up. For more on each approach, see memoization and bottom-up algorithms.

A Harder Example: Longest Common Subsequence

Problem: given two strings, find the longest subsequence they have in common. A subsequence keeps characters in their original order but doesn't have to be contiguous. For example, "ONE" is a subsequence of "LONGEST": LONGEST.

For "STONE" and "LONGEST", the longest common subsequence (LCS) is "ONE", with length 3.

A greedy approach goes wrong here. If you match characters as early as you can, you match the S in "STONE" with the S in "LONGEST", then the T with the T, and you're out of characters: you get "ST", with length 2. To find the best answer, you have to consider both options at every step, and that's what the DP table does.

Define the subproblem

Let table[i][j] be the length of the LCS of the first i characters of the first string and the first j characters of the second string. Then look at the last character of each of those prefixes:

  • If they match, that character extends the LCS of the two shorter prefixes: table[i][j] = table[i - 1][j - 1] + 1.
  • If they don't match, at least one of them isn't in the LCS. So drop one or the other, and keep whichever choice gives the longer LCS: table[i][j] = max(table[i - 1][j], table[i][j - 1]).
  • Base cases: if either prefix is empty, the LCS is empty. So row 0 and column 0 are all zeros.

Fill in the table

Each cell depends only on the cell above it, the cell to its left, and the cell diagonally up and to the left. So if we fill in the table row by row, left to right, every cell's dependencies are already done. Rows are prefixes of "STONE" and columns are prefixes of "LONGEST". The bold cells are the matches that spell out "ONE":

(empty) L O N G E S T
(empty) 0 0 0 0 0 0 0 0
S 0 0 0 0 0 0 1 1
T 0 0 0 0 0 0 1 2
O 0 0 1 1 1 1 1 2
N 0 0 1 2 2 2 2 2
E 0 0 1 2 2 3 3 3

Notice the 2 in the T row, under T: that's the greedy "ST" answer. The table keeps it as one option, but the bottom-right cell, which covers both full strings, ends up with the better answer: 3.

Recover the subsequence

The table gives the length of the LCS. To recover the subsequence itself, start at the bottom-right cell and walk backward:

  1. If the row's character and the column's character match, that character is part of the LCS. Record it and move diagonally up and to the left.
  2. Otherwise, move to whichever neighbor (up or left) holds the larger number.
  3. Stop when you reach row 0 or column 0, then reverse the characters you recorded.

Here, the walk picks up E, then N, then O, which reversed is "ONE". Here's the whole thing in code:

public static String longestCommonSubsequence(String a, String b) { // table[i][j] is the length of the LCS of // the first i characters of a and the first j characters of b int[][] table = new int[a.length() + 1][b.length() + 1]; for (int i = 1; i <= a.length(); i++) { for (int j = 1; j <= b.length(); j++) { if (a.charAt(i - 1) == b.charAt(j - 1)) { // last characters match: extend the LCS of the shorter prefixes table[i][j] = table[i - 1][j - 1] + 1; } else { // no match: drop the last character of a or of b, // whichever leaves the longer LCS table[i][j] = Math.max(table[i - 1][j], table[i][j - 1]); } } } // walk back from the bottom-right corner to recover the subsequence StringBuilder result = new StringBuilder(); int i = a.length(); int j = b.length(); while (i > 0 && j > 0) { if (a.charAt(i - 1) == b.charAt(j - 1)) { result.append(a.charAt(i - 1)); i--; j--; } else if (table[i - 1][j] >= table[i][j - 1]) { i--; } else { j--; } } return result.reverse().toString(); }

For strings of lengths n and m, the table has (n + 1) × (m + 1) cells, and each one takes constant time to fill in. So this takes O(n * m) time and O(n * m) space. If you only need the length, you can keep just two rows of the table at a time (with the shorter string along the columns), bringing the space down to O(min(n, m)).

You could also solve this top-down, by memoizing a recursive method on the pair (i, j). Without the memo, that recursion can take O(2^(n+m)) time. Other two-string problems, like edit distance, use the same shape of table.

How to Solve a Dynamic Programming Problem, Step by Step

  1. Write the brute-force recursive solution. Figure out what choice you make at each step (take 1 step or 2? match these characters, or drop one?) and try every option.
  2. Define the subproblem in words. For example, "ways(i) is the number of ways to climb i steps," or "table[i][j] is the length of the LCS of the first i characters of one string and the first j characters of the other." The values that change from call to call (an index, an amount, a remaining capacity) make up the state.
  3. Write the recurrence. Express the answer for one state in terms of the answers for smaller states.
  4. Pin down the base cases. These are the smallest states, the ones you can answer directly. (See base case.)
  5. Check for overlapping subproblems. Sketch the recursion tree for a small input. If the same state shows up more than once, DP will help.
  6. Add memoization. Save each state's answer the first time you compute it. This is usually the quickest way to go from a slow, correct solution to a fast, correct one.
  7. Convert to bottom-up (optional). Find an order where every state's dependencies come before the state itself, and fill in a table in that order.
  8. Reduce the space (optional). If each entry only looks back a fixed distance (say, one row or two entries), keep only that much of the table.
  9. Analyze the complexity. Time is usually the number of states times the work per state. Space is the size of the table or memo, plus the call stack if you're using recursion.

Dynamic Programming vs. Greedy vs. Divide and Conquer

All three break a problem into smaller pieces. The difference is in how they handle those pieces:

Dynamic programming Greedy Divide and conquer
How it works Solves every distinct subproblem once, stores the answers, and combines them Makes the choice that looks best right now and never reconsiders it Splits the problem into independent parts, solves each one recursively, and combines the results
Subproblems Overlap, so storing their answers pays off Only one is left after each choice Don't overlap, so there's nothing worth storing
Finds the best answer? Yes, as long as the recurrence considers every choice Only for problems where the greedy choice is provably safe Usually used for exact computations, like sorting and searching, rather than optimization
Typical cost Usually polynomial: (number of states) × (work per state), plus memory for the table Often O(n log n) (to sort) or O(n) Often O(n log n), as in merge sort
Examples Longest common subsequence, knapsack, coin change, edit distance Interval scheduling, Dijkstra's algorithm, Huffman coding Merge sort, quicksort, binary search

Making change shows the difference between DP and greedy. With US coins (1, 5, 10, and 25 cents), always grabbing the biggest coin that fits gives you the fewest coins. But with coins worth 1, 3, and 4, greedy makes 6 as 4 + 1 + 1 (three coins), while the best answer is 3 + 3 (two coins). Dynamic programming finds it, because it works out the best answer for every smaller amount instead of committing to the 4 up front.

Time and Space Complexity of Dynamic Programming

A DP solution's running time is usually the number of distinct subproblems times the work to solve each one (once the answers it depends on are known). Here's how that plays out for the examples on this page, with a staircase of n steps and strings of lengths n and m:

Approach Time Space
Climbing stairs, plain recursion O(2^n) O(n) for the call stack
Climbing stairs, memoized O(n) O(n)
Climbing stairs, bottom-up table O(n) O(n)
Climbing stairs, bottom-up keeping only two values O(n) O(1)
LCS, plain recursion O(2^(n+m)) O(n + m) for the call stack
LCS, full DP table O(n * m) O(n * m)
LCS length only, keeping two rows O(n * m) O(min(n, m))

The big win comes from going from plain recursion to memoization or a table. Squeezing the table down to a few rows or values only saves space, not time.

Common Dynamic Programming Interview Problems

Most DP interview questions are variations on a handful of patterns. Recognizing the pattern is often the hardest part, because it tells you what the subproblems are:

  • 1-D sequences (climbing stairs, Fibonacci numbers, house robber, maximum subarray sum). The answer at each position depends on the answers at a few earlier positions. Practice: Compute the nth Fibonacci number.
  • Coin change (the fewest coins for an amount, or the number of ways to make change). Build an amount out of coin denominations you can use as many times as you like. Practice: Making Change, which counts the number of ways.
  • Knapsack (0/1 knapsack, unbounded knapsack, subset sum). Choose items with weights and values to get the most value under a weight limit. Practice: The Cake Thief, where you can take unlimited copies of each cake.
  • Two strings (longest common subsequence, edit distance, longest common substring). A 2-D table over prefixes of both strings, like the LCS example above.
  • Grid paths (unique paths through a grid, minimum path sum). Each cell's answer comes from its neighbors, such as the cell above and the cell to the left.
  • Increasing subsequences (longest increasing subsequence). Track the best answer that ends at each position.
  • Intervals (longest palindromic subsequence, matrix chain multiplication). The answer for a range is built from the answers for smaller ranges inside it.

Dynamic programming builds directly on recursion, so if writing the brute-force recursive solution is the step that trips you up, start there.

Frequently Asked Questions

What is dynamic programming in simple terms?

It's recursion without the repeated work. You break a problem into smaller subproblems, solve each distinct subproblem once, save its answer, and build the final answer from those saved answers.

How do you know if a problem can be solved with dynamic programming?

Look for overlapping subproblems (the same smaller problem comes up again and again) and optimal substructure (the best answer can be built from the best answers to subproblems). Questions that ask for the number of ways, a minimum or maximum, or whether something is possible over a series of choices are common candidates.

What's the difference between memoization and tabulation?

Memoization is top-down: you write the recursive solution and cache each subproblem's answer the first time you compute it. Tabulation is bottom-up: you fill in a table with a loop, starting from the base cases, which avoids recursion and often lets you use less space.

What's the difference between dynamic programming and greedy algorithms?

A greedy algorithm commits to the best-looking choice at each step and never reconsiders it, so it's fast but only correct for some problems. Dynamic programming considers every choice by combining stored answers to subproblems, so it finds the best answer whenever its recurrence is correct.

What's the difference between dynamic programming and divide and conquer?

Both split a problem into subproblems. In divide and conquer, like merge sort, the subproblems are independent and never repeat; dynamic programming is for subproblems that overlap, so storing their answers pays off.

What is the time complexity of dynamic programming?

It's usually the number of distinct subproblems times the work per subproblem. For example, the longest common subsequence of strings of lengths n and m has about n * m subproblems that each take O(1) time, so it runs in O(n * m) time.

Why is it called dynamic programming?

Mathematician Richard Bellman coined the name in the 1950s. 'Programming' meant planning, in the sense of finding the best schedule or plan, not writing code.

Last updated: December 3, 2026

. . .