Skip to main content

Dynamic Programming

Learning objectives
  • Recognize when a problem has optimal substructure and overlapping subproblems — and when greedy is enough
  • Apply a five-step state-design method to derive a recurrence instead of memorizing solutions
  • Convert a memoized recursion into a bottom-up table and compress its space
  • Solve the core families in Go: 1D, 2D over two strings, 0/1 and unbounded knapsack, LIS in O(n log n), edit distance, interval DP
  • Map DP to real problems: cash dispensing, promotion selection, fuzzy name matching, diffs

TL;DR​

  • DP = recursion + reuse. If the brute-force recursion solves the same subproblem many times, cache it (top-down) or fill a table in dependency order (bottom-up).
  • Design the state first: "dp[i] = the best answer for the prefix ending at i" (or for items 0..i with capacity c). Most wrong DP solutions have a wrong or incomplete state.
  • Transition = enumerate the last decision (take or skip item i, which coin was last, which edit was last).
  • Complexity = number of states × cost per transition. Edit distance: (n+1)(m+1) states × O(1) = O(n·m).
  • 0/1 knapsack iterates capacity backwards; unbounded iterates forwards — the loop direction decides whether an item can be reused.
  • LIS in O(n log n): keep the smallest tail for each length and update it with a lower-bound binary search.
  • Interval DP (dp[l][r]) iterates by interval length; it covers "burst balloons", matrix-chain and palindrome partitioning.

When to reach for it​

  • "Count the number of ways", "min/max cost/profit", "is it possible" — and choices at each step affect later options.
  • Greedy feels plausible but you can build a counterexample (coin change with coins 1, 3, 4).
  • "Longest/shortest subsequence" (not contiguous) or two strings compared position by position.
  • A brute-force recursion branches (take/skip, which split point) and you notice repeated arguments.
  • Constraints like n ≤ 1,000–5,000 (O(n²) DP) or amount/capacity ≤ 10⁴ (pseudo-polynomial DP); n ≤ 20 hints at bitmask DP.
  • Grids with only right/down moves, or "partition a sequence into pieces optimally".

Core concepts​

Optimal substructure and overlapping subproblems​

DP applies when (1) an optimal solution is built from optimal solutions to subproblems, and (2) those subproblems repeat. Naive Fibonacci shows the repetition:

fib(3) is computed twice and fib(2) three times; the tree grows exponentially while there are only n distinct subproblems. Divide-and-conquer (merge sort) has optimal substructure but no overlap — no caching needed.

The state-design method​

Use the same five steps for every problem, out loud in interviews:

  1. State: define dp[...] in one English sentence, including what the indexes mean. Add a dimension if the sentence needs "and also…" (capacity, last action, holding stock or not).
  2. Transition: consider the last decision and express dp[state] via smaller states.
  3. Base cases: the smallest states (empty prefix, zero capacity) and "impossible" markers (−1, +∞).
  4. Order: evaluate so every dependency is ready — increasing i, increasing interval length, or just memoize.
  5. Answer: where it lives (dp[n], max(dp), dp[0][n−1]), then optimize space if each row depends only on the previous one.

Applied to House Robber (LeetCode 198, no two adjacent houses): state best(i) = max loot from houses i..n−1; transition: skip house i (best(i+1)) or rob it (nums[i] + best(i+2)); base: best(i) = 0 for i ≥ n; answer best(0).

Top-down vs bottom-up​

// Top-down: recursion plus a memo. Mirrors the recurrence directly.
func robMemo(nums []int) int {
memo := make([]int, len(nums))
for i := range memo {
memo[i] = -1 // not computed yet (real answers are >= 0)
}
var best func(i int) int // best(i) = max loot from houses i..n-1
best = func(i int) int {
if i >= len(nums) {
return 0
}
if memo[i] >= 0 {
return memo[i]
}
memo[i] = max(best(i+1), nums[i]+best(i+2)) // skip i, or rob i
return memo[i]
}
return best(0)
}

// Bottom-up with O(1) space: only the last two states are needed.
func rob(nums []int) int {
prev2, prev1 := 0, 0 // best up to i-2 and up to i-1
for _, v := range nums {
prev2, prev1 = prev1, max(prev1, prev2+v)
}
return prev1
}
Top-down (memo)Bottom-up (table)
DerivationDirect from the recurrence; easiest to get right firstRequires choosing an evaluation order
Work doneOnly reachable statesAll states in the table
SpaceMemo + recursion stack (deep for large n)Table; often compressible to one or two rows
SpeedFunction-call overhead; a map memo is slow — prefer slicesTight loops, cache-friendly
Best forSparse or irregular state spaces, prototypingInterviews after the first draft, production hot paths

2D DP over two sequences​

For two strings a and b, dp[i][j] describes the prefixes a[:i] and b[:j]. Each cell depends on its left, upper and upper-left neighbours, so you fill row by row and keep only two rows.

Longest Common Subsequence (LCS) uses the same grid: dp[i][j] = dp[i−1][j−1] + 1 on a match, else max(dp[i−1][j], dp[i][j−1]). LCS is the core of diff — and of reconciling two ordered statement files line by line (Reconciliation & Settlement).

Knapsack: 0/1 vs unbounded​

dp[c] = best value with total weight at most c. The only difference between the variants is the loop direction over capacity:

// knapsack01: each item used at most once.
func knapsack01(weights, values []int, capacity int) int {
dp := make([]int, capacity+1)
for i := range weights {
for c := capacity; c >= weights[i]; c-- { // backwards: dp[c-w] is still "without item i"
dp[c] = max(dp[c], dp[c-weights[i]]+values[i])
}
}
return dp[capacity]
}

// knapsackUnbounded: unlimited copies of each item.
func knapsackUnbounded(weights, values []int, capacity int) int {
dp := make([]int, capacity+1)
for i := range weights {
for c := weights[i]; c <= capacity; c++ { // forwards: dp[c-w] may already include item i
dp[c] = max(dp[c], dp[c-weights[i]]+values[i])
}
}
return dp[capacity]
}

Complexity O(n·C) — pseudo-polynomial: polynomial in the value of C, exponential in its number of bits. Knapsack is NP-hard in general; this works because capacities in interview problems (and in cents-denominated budgets of moderate size) are small. E-commerce reading: choose which promotions or vouchers to apply under a budget or stacking limit to maximize discount (Pricing & Promotions).

LIS: O(n²) and O(n log n)​

dp[i] = length of the longest increasing subsequence ending at i, giving O(n²). The faster method keeps tails[k] = the smallest possible tail value of an increasing subsequence of length k+1; tails stays sorted, so each element is placed with a lower-bound binary search (Problem 2).

func lengthOfLISQuadratic(nums []int) int {
dp := make([]int, len(nums)) // dp[i] = LIS ending exactly at i
best := 0
for i := range nums {
dp[i] = 1
for j := range i {
if nums[j] < nums[i] {
dp[i] = max(dp[i], dp[j]+1)
}
}
best = max(best, dp[i])
}
return best
}

Interval DP​

When the answer for a range depends on how you split it, use dp[l][r] and iterate by increasing length so smaller intervals are ready. Burst Balloons (LeetCode 312) is the classic: think of k as the last balloon burst between l and r, so its neighbours at that moment are exactly l and r.

// maxCoins: dp[l][r] = best coins from bursting every balloon strictly
// between l and r, with l and r still present.
func maxCoins(nums []int) int {
vals := make([]int, 0, len(nums)+2)
vals = append(vals, 1)
vals = append(vals, nums...)
vals = append(vals, 1)
n := len(vals)
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
for length := 2; length < n; length++ { // distance between l and r
for l := 0; l+length < n; l++ {
r := l + length
for k := l + 1; k < r; k++ { // k is the last balloon burst in (l, r)
dp[l][r] = max(dp[l][r], dp[l][k]+vals[l]*vals[k]*vals[r]+dp[k][r])
}
}
}
return dp[0][n-1]
}

O(n³) time, O(n²) space. Other DP shapes worth recognizing: bitmask DP over subsets (n ≤ 20, travelling salesman), DP on trees (post-order returning a small tuple, House Robber III), state-machine DP (stock trading with cooldown or fees: states "holding" and "not holding"), and DP on DAGs (longest path in topological order — Bellman-Ford itself is DP over "at most k edges").

Reconstructing the solution​

Interviewers often ask for the actual items/edits, not just the number. Either store the choice made at each state, or walk the finished table backwards from the answer, re-checking which transition produced each value. Keep the full table (not the compressed rows) if you need reconstruction.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Plain recursionSimplest to writeExponential with overlapTiny inputs, deriving the recurrence
Top-down memoMirrors the recurrence, computes only reachable statesStack depth, call overheadSparse state spaces, first working version
Bottom-up tableFast, no recursion, enables reconstructionMust pick evaluation order; computes all statesDense state spaces, production code
Space-optimized rowsO(m) instead of O(n·m) memoryLoses reconstructionOnly the value is needed, large inputs
GreedyO(n) or O(n log n), simpleWrong unless the greedy-choice property holdsYou can prove it (Greedy & Backtracking)
Backtracking with pruningFinds all solutionsExponentialNeed every solution, or n is tiny

In practice​

Problem 1 — Coin Change (LeetCode 322)​

Problem. Given coin denominations and an amount, return the fewest coins that make the amount, or −1.

Approach. Greedy (largest coin first) fails for coins 1, 3, 4 and amount 6: greedy gives 4 + 1 + 1 (three coins), the optimum is 3 + 3 (two). State: dp[a] = fewest coins summing to a. Transition: the last coin is some c, so dp[a] = 1 + min over c of dp[a − c]. Base dp[0] = 0; "impossible" is a large sentinel that cannot overflow when 1 is added.

func coinChange(coins []int, amount int) int {
const inf = math.MaxInt / 2 // safe to add 1 without overflow
dp := make([]int, amount+1) // dp[a] = fewest coins summing to a
for a := 1; a <= amount; a++ {
dp[a] = inf
for _, c := range coins {
if c <= a && dp[a-c]+1 < dp[a] {
dp[a] = dp[a-c] + 1
}
}
}
if dp[amount] >= inf {
return -1
}
return dp[amount]
}

Complexity. O(amount × coins) time, O(amount) space. Canonical systems (most national currencies) happen to make greedy optimal with unlimited notes; an ATM with limited note counts is a bounded knapsack where greedy can fail even then (see the exercise).

Problem 2 — Longest Increasing Subsequence (LeetCode 300)​

Problem. Return the length of the longest strictly increasing subsequence.

Approach. Patience sorting. For each value v, find the first tail ≥ v: replacing it keeps every length achievable with a smaller (better) tail; if no tail is ≥ v, v extends the longest subsequence.

// lengthOfLIS: tails[k] is the smallest tail of an increasing subsequence of length k+1.
func lengthOfLIS(nums []int) int {
var tails []int
for _, v := range nums {
i, _ := slices.BinarySearch(tails, v) // first tail >= v
if i == len(tails) {
tails = append(tails, v)
} else {
tails[i] = v
}
}
return len(tails)
}

Complexity. O(n log n) time, O(n) space. tails is not itself a valid subsequence; to reconstruct one, store for each element the index of its predecessor. For non-decreasing subsequences, search for the first tail > v instead (upper bound).

Problem 3 — Edit Distance (LeetCode 72)​

Problem. Minimum insertions, deletions and replacements to turn string a into string b (Levenshtein distance).

Approach. dp[i][j] = distance between a[:i] and b[:j]. If the last characters match, dp[i][j] = dp[i−1][j−1]; otherwise 1 + the minimum of replace (dp[i−1][j−1]), delete (dp[i−1][j]) and insert (dp[i][j−1]). Base: transforming to or from the empty string costs its length. Only the previous row is needed.

// minDistance returns the Levenshtein distance between a and b (byte-wise).
func minDistance(a, b string) int {
prev := make([]int, len(b)+1) // row i-1
curr := make([]int, len(b)+1) // row i
for j := range prev {
prev[j] = j // "" -> b[:j]: j inserts
}
for i := 1; i <= len(a); i++ {
curr[0] = i // a[:i] -> "": i deletes
for j := 1; j <= len(b); j++ {
if a[i-1] == b[j-1] {
curr[j] = prev[j-1]
} else {
curr[j] = 1 + min(prev[j-1], prev[j], curr[j-1]) // replace, delete, insert
}
}
prev, curr = curr, prev
}
return prev[len(b)]
}

Complexity. O(n·m) time, O(m) space. Compliance reading: sanctions and watch-list screening compares customer names against lists with fuzzy matching (edit distance, Jaro–Winkler, phonetic keys) so "Mohammed" and "Muhammad" still hit; for Vietnamese or other non-ASCII names convert to []rune (and normalize diacritics) before comparing (Compliance: PCI DSS, KYC/AML, Data Protection). At list scale you cannot compare every pair — you block candidates first (by phonetic key or n-grams) and run edit distance only on those.

Problem 4 — Partition Equal Subset Sum (LeetCode 416)​

Problem. Can the numbers be split into two subsets with equal sums?

Approach. Equivalent to "is there a subset summing to total/2?" — a 0/1 knapsack over booleans. Iterate sums backwards so each number is used at most once.

func canPartition(nums []int) bool {
total := 0
for _, v := range nums {
total += v
}
if total%2 != 0 {
return false
}
target := total / 2
reach := make([]bool, target+1) // reach[s] = some subset sums to s
reach[0] = true
for _, v := range nums {
for s := target; s >= v; s-- { // backwards: each number at most once
reach[s] = reach[s] || reach[s-v]
}
}
return reach[target]
}

Complexity. O(n × total) time, O(total) space. A math/big.Int or []uint64 bitset makes it far faster: reach |= reach << v processes 64 sums per word.

Practice list​

  • Easy: Climbing Stairs (70), Min Cost Climbing Stairs (746), Pascal's Triangle (118), Counting Bits (338)
  • Medium: House Robber (198), Coin Change (322), Longest Increasing Subsequence (300), Unique Paths (62), Longest Common Subsequence (1143), Word Break (139), Decode Ways (91), Partition Equal Subset Sum (416), Target Sum (494), Longest Palindromic Substring (5), Edit Distance (72)
  • Hard: Burst Balloons (312), Regular Expression Matching (10), Distinct Subsequences (115), Longest Valid Parentheses (32)

Common pitfalls​

  • Incomplete state. The recurrence needs information the state does not carry (e.g. whether you hold a stock, how many transactions remain). Symptom: correct on small cases, wrong on others.
  • Wrong knapsack loop direction — forwards for 0/1 silently reuses items.
  • Sentinel bugs: using 0 as "impossible" in a min-DP, or math.MaxInt then adding 1 (overflow to negative, which then wins every min).
  • Off-by-one between table and string indexes — dp[i] describes s[:i], so the character is s[i−1].
  • map memo keyed by fmt.Sprintf — orders of magnitude slower than a slice; use slices or array/struct keys.
  • Deep top-down recursion for n = 10⁵–10⁶; convert to bottom-up.
  • Forcing DP where greedy is provably optimal (interval scheduling), wasting time — or the reverse: greedy where DP is needed (coin change).
  • Bytes vs runes in string DP over user-entered names.

Interview angle​

  • Narrate the five steps: state in words, transition, base cases, order, answer — then complexity as "states × transition cost". This structure is what interviewers grade; a memorized table without justification is a red flag.
  • Start top-down if unsure (it follows the recurrence), then offer bottom-up and space compression as the optimization.
  • Expect "can you reconstruct the actual solution?" and "can you reduce memory?" — know which one prevents the other.
  • Explain why greedy fails with a concrete counterexample; it shows you considered the simpler approach.
  • Architect angle: DP shows up in pricing engines (best promotion combination), routing and allocation, text matching in compliance, and diffing in reconciliation. Mention when exactness is too expensive and heuristics or ILP solvers take over.
  • Red flags: inability to define the state in a sentence, or jumping between unrelated formulas.

Self-check​

1. What two properties make a problem suitable for DP, and which one does merge sort lack?

Optimal substructure (an optimal answer combines optimal sub-answers) and overlapping subproblems (the same subproblem recurs). Merge sort has optimal substructure but its subproblems are disjoint halves that never repeat, so caching gains nothing — it is plain divide-and-conquer.

2. Why does the 0/1 knapsack iterate capacity downwards while the unbounded version iterates upwards?

With a 1D table, dp[c − w] must refer to the state before item i is considered for 0/1. Iterating downwards updates large capacities first, so dp[c − w] is still the old value. Iterating upwards means dp[c − w] may already include item i, which allows reusing it — exactly what the unbounded variant wants.

3. Explain the O(n log n) LIS algorithm in your own words.

Maintain tails, where tails[k] is the smallest possible last value of any increasing subsequence of length k+1 seen so far; it is sorted. For each new value, binary-search the first tail ≥ it: replace that tail (a smaller tail is never worse), or append if the value exceeds every tail (the longest subsequence grows). The answer is len(tails).

4. What are the states, transitions and complexity of edit distance?

State dp[i][j] = edits to turn a[:i] into b[:j]. If a[i−1] == b[j−1] it equals dp[i−1][j−1]; otherwise 1 + min(replace dp[i−1][j−1], delete dp[i−1][j], insert dp[i][j−1]). Base cases are the first row and column (i or j). O(n·m) time, O(min(n, m)) space with two rows.

5. Why is the knapsack DP called pseudo-polynomial?

Its running time O(n·C) is polynomial in the numeric value of C, but input size measures C by its number of bits, log C. Doubling the number of bits squares C, so the algorithm is exponential in input size. It is practical only when C is small.

6. Why do you iterate by interval length in interval DP?

dp[l][r] depends on dp[l][k] and dp[k][r] for l < k < r — strictly shorter intervals. Iterating by increasing length guarantees all shorter intervals are computed first. Iterating l from 0 upward would read dp[k][r] for larger k before it is filled.

7. Scenario: a checkout must pick the best combination of up to 3 stackable vouchers from 30 the user owns, respecting a minimum-basket rule per voucher. DP, greedy or brute force?

With at most 3 of 30, brute force is C(30,3) ≈ 4,060 combinations — trivially fast and easy to audit, which matters when customer support must explain the price. Greedy (largest discount first) can be wrong when vouchers interact (percentage vs fixed, thresholds). DP pays off when the limit or catalogue grows (knapsack over budget/stacking slots). Whatever you choose, make the result deterministic and log the evaluated combination.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Write an ATM dispenser that pays an amount with the fewest notes given limited note counts (a bounded knapsack):

  1. Dispense(amount int64, notes map[int64]int) (map[int64]int, error) — DP over amount in units of the smallest denomination, tracking the choice per state for reconstruction.
  2. Show greedy failing: with notes 500,000 × 1 and 200,000 × 3 (no 100,000), amount 600,000 — greedy takes 500,000 and gets stuck; DP returns 200,000 × 3.
  3. Add a property test: DP's note count is never larger than greedy's whenever greedy succeeds.

Done when tests pass, the function returns a typed error when the amount is impossible, and you can state its complexity in terms of amount/unit and number of denominations.

Further reading​

  • Introduction to Algorithms (CLRS) — dynamic programming chapter (rod cutting, matrix chain, LCS)
  • Steven Skiena, The Algorithm Design Manual — dynamic programming chapter and its "war stories"
  • MIT 6.006 Introduction to Algorithms (Spring 2020, Erik Demaine et al., MIT OpenCourseWare) — the dynamic programming lectures and their SRTBOT framework
  • Richard Bellman, Dynamic Programming (1957) — the origin of the term
  • NeetCode 150 — "1-D Dynamic Programming" and "2-D Dynamic Programming" sections (neetcode.io)
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).