Dynamic Programming and Greedy Algorithms
Turn exponential recursion into linear time with memoization, solve classic DP problems, and learn when a greedy choice is optimal and when it fails.
Welcome back!
Step 1 of 12Learn
Stop solving the same problem twice
Remember naive recursive Fibonacci: fib(40) makes over 300 million calls because it recomputes the same values again and again. Yet there are only 41 distinct values, fib(0) through fib(40). If we remembered each one the first time we computed it, the work would collapse to about 40 steps.
That's the core of dynamic programming (DP): solve each subproblem once, store the answer, and reuse it. DP applies when a problem has two properties:
- Overlapping subproblems: the same smaller problems come up repeatedly.
- Optimal substructure: the best solution to the whole problem can be built from the best solutions to its subproblems.
There are two ways to implement it:
- Top-down with memoization: write the natural recursive solution, then add a cache, such as a Map. Before computing, check the cache; after computing, store the result. For Fibonacci, this makes each fib(k) computed once: O(n) time.
- Bottom-up with tabulation: fill a table from the smallest subproblems upward. For Fibonacci: start with fib(0) and fib(1), then compute fib(2), fib(3) and so on in a loop. Since each value depends only on the previous two, you can even keep just two variables: O(n) time and O(1) space.
Top-down is often easier to write from a recursive idea; bottom-up avoids recursion depth limits and is usually a bit faster. Both trade memory for time, the same bargain hash tables offer.
Step 2 of 12Try the calculator
Naive recursion versus memoization
Naive fib(n) makes 2·F(n+1) − 1 calls, where F is the Fibonacci sequence. A memoized version computes each of the n + 1 values fib(0)…fib(n) only once.
- Naive calls
- 2,692,537
- Distinct subproblems (memoized)
- 31
Step 3 of 12Practice · Code challenge
You can climb a staircase 1 or 2 steps at a time. Write climbStairs(n) that returns the number of distinct ways to reach step n (for n ≥ 1), using a bottom-up loop so it runs in O(n) time. For example, there are 3 ways to climb 3 steps: 1+1+1, 1+2 and 2+1.
climbStairs(1)climbStairs(2)climbStairs(3)climbStairs(5)climbStairs(10)climbStairs(45)
Step 4 of 12Learn
Solving a DP problem step by step
Most DP solutions follow the same recipe:
- Define the state: what does a subproblem look like? For example, best[x] = the minimum number of coins needed to make amount x.
- Write the recurrence: how does a state depend on smaller ones? best[x] = 1 + the minimum of best[x − c] over every coin c ≤ x.
- Set base cases: best[0] = 0, since zero coins make zero.
- Choose an order: compute states so that every dependency is ready, here from x = 1 up to the target.
- Read the answer from the right state, best[target], and analyze the cost: number of states times work per state.
With coins {1, 3, 4} and target 6: best[1] = 1, best[2] = 2, best[3] = 1, best[4] = 1, best[5] = 2 (4 + 1), and best[6] = 2 (3 + 3). With k coin types and target T, there are T states, each checking k coins: O(T·k).
Other classic DP problems:
- Longest common subsequence of two strings, used in diff tools and DNA comparison: a 2D table over prefixes of both strings, O(m·n).
- 0/1 knapsack: choose items with weights and values to maximize value without exceeding a capacity.
- Edit distance: the fewest insertions, deletions and substitutions to turn one word into another, used in spell checkers.
The hardest step is usually the first one. Ask: if I knew the answers to smaller versions of this problem, how would I combine them?
Step 5 of 12Practice · Work it out
Using coins worth 1, 3 and 4, what is the minimum number of coins needed to make exactly 6?
Step 6 of 12Learn
Greedy algorithms
A greedy algorithm builds a solution step by step, always making the choice that looks best right now, and never reconsidering. Greedy algorithms are usually simple and fast. The catch is that they're only correct for problems with the greedy-choice property: making the locally best choice never prevents reaching the globally best solution.
When greedy works:
- Making change with US coins (25, 10, 5, 1 cents): taking the largest coin that fits always gives the fewest coins.
- Activity selection: to schedule the most non-overlapping meetings in one room, repeatedly pick the meeting that ends earliest. Picking the shortest or the earliest-starting meeting can fail; earliest-ending is provably optimal.
- Dijkstra's algorithm greedily finalizes the closest unvisited vertex, which is correct when edge weights are non-negative.
- Huffman coding, used in compression, greedily merges the two least frequent symbols.
- Minimum spanning trees with Kruskal's or Prim's algorithm.
When greedy fails: with coins {1, 3, 4} and a target of 6, greedy takes 4, then 1, then 1 for three coins, while 3 + 3 uses two. The 0/1 knapsack problem is another: grabbing the item with the best value-per-weight ratio first can leave wasted capacity.
The lesson is to be suspicious of greedy solutions until you can argue why they're correct, often with an exchange argument: show that any optimal solution can be changed to include the greedy choice without getting worse. If you find a counterexample, reach for dynamic programming.
Step 7 of 12Practice · True or false
Always taking the largest coin that fits gives the minimum number of coins for every possible set of coin values.
Step 8 of 12Compare
Greedy or dynamic programming?
| Aspect | Greedy | Dynamic programming |
|---|---|---|
| Idea | Take the best-looking choice now, never revisit | Solve every subproblem once, combine the best |
| Speed | Usually very fast | States × work per state |
| Correct when | The greedy-choice property holds (US coins) | Optimal substructure + overlapping subproblems |
| Coins 1, 5, 6 for 10 | 6 + 1 + 1 + 1 + 1 = 5 coins | 5 + 5 = 2 coins |
Step 9 of 12Learn
Choosing an approach
Faced with a new problem, experienced programmers move through a few questions rather than guessing.
1. What's the brute force? Write down the obvious solution and its complexity, such as checking every pair (O(n²)) or every subset (O(2ⁿ)). It's a baseline and often reveals the structure.
2. What do the constraints allow? With roughly 10⁸ simple operations per second, input size tells you what complexity you need. For n up to about 20, exponential may be fine. For n up to a few thousand, O(n²) works. For n around 10⁵ to 10⁶, you need O(n log n) or O(n).
3. Where is work repeated?
- Repeated searching for values: use a hash table.
- Repeated subproblems in recursion: use dynamic programming.
- Repeatedly needing the smallest or largest: use a heap.
- Searching sorted data or a monotonic answer: use binary search.
4. Would sorting help? Many problems become easy on sorted data: finding duplicates, pairing elements, merging intervals, greedy scheduling. Sorting costs O(n log n), which is often affordable.
5. Is there structure to model? Connections suggest a graph and BFS or DFS; hierarchy suggests a tree; nested or most-recent-first patterns suggest a stack.
Finally, verify: test edge cases (empty input, one element, duplicates, negative numbers), and recheck the complexity of every line, including hidden costs in built-in methods.
Step 10 of 12Practice · Match the pairs
Match each problem to the technique that most directly improves on brute force.
Tap an answer, then tap the place where it belongs (or drag it there).
- Count the ways to reach the bottom-right of a grid moving only right or down
- Find whether any two numbers in an array sum to a target
- Schedule the maximum number of non-overlapping talks in one room
- Find the smallest shipping capacity that delivers everything within 5 days
- Find the fewest flights between two airports
Step 11 of 12Note
Step 12 of 12Practice · What would you do?
What would you do?
A problem asks for the longest increasing subsequence of an array with up to 2,000 numbers. Your first idea is to try every possible subsequence. What's the best next step?
Lesson complete!