Skip to content
Chethan Yadav_
Data Structures & Algorithms

DSA/Lesson 11 of 11/6 min read

Dynamic Programming and Greedy

Optimal substructure, memoization vs tabulation, classic DP patterns like knapsack and LCS, and when greedy algorithms are correct.


On this page

Dynamic Programming

Dynamic programming (DP) solves a problem by breaking it into subproblems, solving each once, and storing the results. It applies when a problem has two properties.

Optimal Substructure

An optimal solution is built from optimal solutions of subproblems. Shortest paths have it: the shortest path from A to C via B contains the shortest path from A to B.

Overlapping Subproblems

The same subproblems are solved many times by naive recursion. Fibonacci: fib(n) needs fib(n-1) and fib(n-2), which share fib(n-3), and so on.

Memoization

Top-down: write the natural recursion, then cache results.

from functools import lru_cache
 
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

Easy to write and only computes states that are actually needed, but recursion depth can overflow the stack.

Tabulation

Bottom-up: fill a table in an order where dependencies are already computed.

def fib(n):
    if n < 2:
        return n
    prev, cur = 0, 1
    for _ in range(n - 1):
        prev, cur = cur, prev + cur
    return cur

No recursion overhead, and often allows space optimization (keep only the last row or last two values).

MemoizationTabulation
DirectionTop-downBottom-up
ImplementationRecursion + cacheLoops + table
States computedOnly needed onesAll
Stack overflow riskYesNo
Space optimizationHarderEasy

How to solve a DP problem

  1. Define the state: what does dp[i] (or dp[i][j]) mean, in words?
  2. Write the recurrence: how does a state depend on smaller states?
  3. Base cases: smallest states with known answers.
  4. Order of computation: make sure dependencies are filled first.
  5. Answer: which state (or max over states) is the result?
  6. Optimize space if only recent rows are used.

Time complexity is usually number of states * work per state.

Classic DP patterns

1D DP

  • Climbing stairs: dp[i] = dp[i-1] + dp[i-2].
  • House robber: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
  • Coin change (min coins): dp[a] = min(dp[a - c] + 1) over coins c. O(amount * coins).
  • Word break: dp[i] is true if some dp[j] is true and s[j:i] is in the dictionary.

0/1 Knapsack

Items with weight w[i] and value v[i], capacity W; each item taken at most once.

dp[i][c] = max(dp[i-1][c],                 # skip item i
               dp[i-1][c - w[i]] + v[i])   # take item i, if it fits

O(n * W) time. Space-optimize to one array by iterating capacity backwards so each item is used once. Iterating forwards gives the unbounded knapsack (items reusable). Note this is pseudo-polynomial: W is a number, not an input size.

Variants: subset sum, partition equal subset sum, target sum.

Longest Common Subsequence

if a[i-1] == b[j-1]:  dp[i][j] = dp[i-1][j-1] + 1
else:                 dp[i][j] = max(dp[i-1][j], dp[i][j-1])

O(m * n). Used in diff tools and DNA alignment. A subsequence keeps order but need not be contiguous; a substring must be contiguous.

Longest Increasing Subsequence

  • O(n^2): dp[i] = 1 + max(dp[j]) for j before i with smaller value.
  • O(n log n): keep tails[k] = smallest tail of an increasing subsequence of length k + 1, and binary search where each new element goes.

Edit Distance

Minimum inserts, deletes and replacements to turn a into b (Levenshtein).

if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1]
else: dp[i][j] = 1 + min(dp[i-1][j],     # delete
                         dp[i][j-1],     # insert
                         dp[i-1][j-1])   # replace

Other families

FamilyExamples
Grid DPUnique paths, minimum path sum
Interval DPMatrix chain multiplication, burst balloons
DP on treesHouse robber III, tree diameter
Bitmask DPTravelling salesman O(2^n * n^2)
State machine DPStock buy and sell with cooldown

Greedy Algorithm

A greedy algorithm makes the locally best choice at each step and never reconsiders. It is usually simpler and faster than DP, but only correct for some problems.

Greedy Choice Property

A globally optimal solution can be reached by making a locally optimal choice first. Together with optimal substructure, this makes greedy correct. Prove it with an exchange argument: show any optimal solution can be transformed to include the greedy choice without getting worse.

When greedy fails

Coin change with coins [1, 3, 4] and amount 6: greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 uses 2. Use DP. Greedy works for canonical coin systems like [1, 5, 10, 25].

Similarly, fractional knapsack is greedy (sort by value per weight), but 0/1 knapsack needs DP.

Activity Selection

Choose the maximum number of non-overlapping intervals: sort by end time, and repeatedly pick the next activity that starts after the last chosen one ends. O(n log n).

Related interval problems:

ProblemGreedy rule
Non-overlapping intervals (min removals)Sort by end, count overlaps
Merge intervalsSort by start, merge if overlapping
Meeting rooms IISort starts and ends, or min-heap of end times
Minimum arrows to burst balloonsSort by end

Huffman Coding

Optimal prefix-free code for data compression. Repeatedly merge the two lowest-frequency nodes (min-heap) into a new node until one tree remains. Frequent characters get shorter codes. O(n log n).

Other greedy classics: jump game, gas station, task scheduler, Dijkstra, Prim and Kruskal.

DP vs greedy vs divide and conquer

GreedyDPDivide and conquer
ChoicesOne local choiceTry all, keep bestSplit
SubproblemsOne remainsOverlappingIndependent
CorrectnessNeeds proofAlways (if state is right)Always
SpeedFastestSlowerVaries

Quick revision

  • DP needs optimal substructure and overlapping subproblems.
  • Memoization is top-down recursion plus cache; tabulation is bottom-up loops.
  • Define the state in words first, then the recurrence, base cases and order.
  • 0/1 knapsack: iterate capacity backwards in 1D; forwards gives unbounded.
  • LCS and edit distance are O(m * n) grid DPs; LIS can be O(n log n).
  • Greedy needs the greedy choice property; prove with an exchange argument.
  • Coin change with arbitrary coins and 0/1 knapsack break greedy; use DP.
  • Interval scheduling: sort by end time.