Angad Sandhu
Search
Browse
On this page

15. Dynamic Programming, Part 1: SRTBOT, Fib, DAGs, Bowling

15. Dynamic Programming, Part 1: SRTBOT, Fib, DAGs, Bowling

Overview

This lecture introduces Dynamic Programming (DP), the most powerful algorithmic design paradigm. DP is a particular type of recursive algorithm design that uses memoization to reuse previously computed solutions.

Key insight: All algorithms are recursive at some level because we write constant-sized code to solve problems of arbitrary size n.


SRTBOT Framework

A systematic approach to designing recursive algorithms:

LetterStepDescription
SSubproblemsDefine what subproblems to solve (want polynomial count)
RRelationsWrite recurrence relating subproblems
TTopological OrderEnsure subproblem dependencies form a DAG (acyclic)
BBase CasesDefine solutions for smallest subproblems
OOriginal ProblemExpress the original problem using subproblems
TTime AnalysisAnalyze running time

Dynamic Programming = SRTBOT + Memoization

Subproblems (S) - Deep Dive

The hardest part of designing a DP algorithm is figuring out what the subproblems should be.

What is a Subproblem?

A subproblem is a smaller instance of the original problem (or a related problem) that:

  1. Can be solved independently
  2. Can be combined to solve larger problems
  3. Has overlapping instances (same subproblem needed multiple times)

Key Requirements

RequirementWhy It Matters
Polynomial countIf exponential subproblems, DP gives no speedup
Self-reducibleLarger subproblems must reduce to smaller ones
OverlapWithout overlap, memoization provides no benefit

Subproblem Design Strategies

Strategy 1: Input Reduction (for sequences)

TypeNotationCountWhen to Use
Prefixesx[:i]Θ(n)When solution builds left-to-right
Suffixesx[i:]Θ(n)When solution builds right-to-left
Substringsx[i:j]Θ(n²)When need arbitrary contiguous segments

Strategy 2: Add Constraints/Parameters

Sometimes the original problem isn't enough. Add extra parameters:

Original:       "Find longest path in graph"
With parameter: "Find longest path ending at vertex v"
                Now we have |V| subproblems instead of 1

Strategy 3: Problem Transformation

Original ProblemSubproblem Formulation
Shortest path s→tShortest path s→v for all v
Max score in gameMax score from position i onward
Optimal structureOptimal structure using first i elements

Common Mistakes

  1. Too few subproblems: Can't express recurrence
  2. Too many subproblems: Exponential time (e.g., all subsequences = 2^n)
  3. Wrong parameterization: Can't reduce to smaller subproblems
  4. Circular dependencies: Subproblems depend on each other cyclically

The Art of Subproblem Design

Ask yourself:

  • "What information do I need to solve the rest of the problem?"
  • "If I knew X, could I reduce to a smaller instance?"
  • "What's the minimum state I need to track?"

The answer to these questions defines your subproblems.

Relations (R) - Deep Dive

The relation (or recurrence) is the heart of the DP algorithm—it defines how to compute a subproblem from smaller subproblems.

Anatomy of a Recurrence

Subproblem(params) = COMBINE( Subproblem(smaller_params₁),
                              Subproblem(smaller_params₂),
                              ... ,
                              local_computation )

Components:

  1. Left side: The subproblem we're solving
  2. Right side: Expression using smaller subproblems
  3. Combine function: How to merge results (max, min, +, ×, or, and)
  4. Local computation: Work done at this level (not recursive)

The "Local Brute Force" Principle

The key insight for writing recurrences:

Identify ONE decision/feature, try ALL options for that decision, recurse on the rest

Problem TypeDecision to MakeOptions to Try
Optimization (max/min)What's the first/last choice?All valid choices, take max/min
CountingWhat's the first/last element?All possibilities, sum them
Boolean (exists?)Does solution use element i?Yes or No, take OR

Writing Recurrences: Step-by-Step

Step 1: Define what you're computing

B(i) = "maximum score achievable using pins i through n-1"

Step 2: Identify the first decision point

"What do I do with pin i?"
Options: skip it, hit it alone, hit it with pin i+1

Step 3: For each option, express result using smaller subproblems

Skip pin i:        B(i+1)                    # remaining pins
Hit pin i alone:   v[i] + B(i+1)             # score + remaining
Hit i and i+1:     v[i]*v[i+1] + B(i+2)      # score + remaining

Step 4: Combine with appropriate function

B(i) = max(B(i+1), v[i] + B(i+1), v[i]*v[i+1] + B(i+2))

Common Recurrence Patterns

Pattern 1: Linear Sequence (Suffix)

DP(i) = best of:
    - DP(i+1)                    # skip/ignore element i
    - f(i) + DP(i+1)             # use element i, move to next
    - g(i,i+1) + DP(i+2)         # use elements i and i+1 together

Pattern 2: Linear Sequence (Prefix)

DP(i) = best of:
    - DP(i-1)                    # skip/ignore element i
    - f(i) + DP(i-1)             # use element i
    - g(i-1,i) + DP(i-2)         # use elements i-1 and i together

Pattern 3: DAG/Graph

DP(v) = combine over all incoming edges (u,v):
    - DP(u) ⊕ weight(u,v)

Pattern 4: Interval/Substring

DP(i,j) = best of:
    - DP(i+1,j)                  # exclude left endpoint
    - DP(i,j-1)                  # exclude right endpoint
    - DP(i+1,j-1) + f(i,j)       # use both endpoints
    - max over k: DP(i,k) + DP(k,j)  # split in middle

Verifying Your Recurrence

Checklist:

  • Does it compute what the subproblem definition says?
  • Are all recursive calls to strictly smaller subproblems?
  • Are all cases covered (no missing options)?
  • Is the combine function correct (max for maximize, min for minimize)?
  • Is the non-recursive work polynomial?

Example: Why Fibonacci Works

Subproblem: F(i) = ith Fibonacci number
Recurrence: F(i) = F(i-1) + F(i-2)

✓ Computes Fibonacci by definition
✓ i-1 < i and i-2 < i (smaller subproblems)
✓ All cases: either base case or use recurrence
✓ Combine: addition (correct for Fibonacci)
✓ Non-recursive work: O(1) addition

Example: Why DAG Shortest Paths Works

Subproblem: δ(s,v) = shortest path weight from s to v
Recurrence: δ(s,v) = min over incoming (u,v): δ(s,u) + w(u,v)

✓ Computes shortest path (optimal substructure property)
✓ u comes before v in topological order (smaller in DAG sense)
✓ All cases: consider all ways to reach v
✓ Combine: min (correct for shortest path)
✓ Non-recursive work: O(in-degree of v)

Topological Order (T) - Deep Dive

The topological order ensures that when we solve a subproblem, all subproblems it depends on have already been solved. This prevents infinite loops and guarantees correctness.

The Subproblem DAG

Every DP defines an implicit subproblem dependency graph:

  • Vertices: Each subproblem is a vertex
  • Edges: Draw edge from A → B if solving B requires the solution to A
Example: Fibonacci subproblem graph

F(1) ──→ F(2) ──→ F(3) ──→ F(4) ──→ F(5) ──→ F(6)
           │       ↑       ↑       ↑       ↑
           └───────┘       │       │       │
                   └───────┘       │       │
                           └───────┘       │
                                   └───────┘

Why Acyclic?

Critical requirement: The subproblem graph must be a DAG (Directed Acyclic Graph).

If Graph Has...Result
No cycles (DAG)✓ Algorithm terminates, correct answer
Cycle✗ Infinite recursion, stack overflow

If A depends on B, and B depends on A, neither can be computed first!

How to Specify Topological Order

Method 1: Explicit For Loop

# Fibonacci: increasing order
for i in range(1, n+1):
    compute F(i)

# Bowling (suffix): decreasing order  
for i in range(n, -1, -1):
    compute B(i)

# 2D substrings: increasing length
for length in range(1, n+1):
    for i in range(n - length + 1):
        j = i + length
        compute DP(i, j)

Method 2: Implicit via Recursion + Memoization

The recursive algorithm with memoization automatically computes in valid topological order:

  • DFS through subproblem graph
  • Memo table acts as "visited" marker
  • Finish order = reverse topological order
def solve(subproblem):
    if subproblem in memo:      # Already computed
        return memo[subproblem]
    # Recurse on dependencies first (they get computed before us)
    result = combine(solve(dep1), solve(dep2), ...)
    memo[subproblem] = result
    return result

Common Topological Orders

Subproblem TypeTypical Order
Prefixes x[:i]Increasing i: 0, 1, 2, ..., n
Suffixes x[i:]Decreasing i: n, n-1, ..., 0
Substrings x[i:j]Increasing (j-i): length 1, 2, ..., n
Graph verticesTopological sort of graph
2D grid (i,j)Row by row, or by diagonal

Proving Acyclicity

To prove your subproblem graph is acyclic, show one of:

  1. Explicit ordering: Define a total order where dependencies always go "backward"

    F(i) depends on F(i-1), F(i-2)
    Since i-1 < i and i-2 < i, dependencies go to smaller indices ✓
  2. Size argument: Dependencies always have strictly smaller "size"

    B(i) depends on B(i+1), B(i+2)
    Suffix starting at i+1 is shorter than suffix at i ✓
  3. Graph structure: For graph problems, the input graph is already a DAG

Base Cases (B) - Deep Dive

Base cases are the foundation of the recursion—the smallest subproblems that can be solved directly without further recursion.

Role of Base Cases

Recursion without base case = Infinite loop

Base cases provide:

  1. Termination: Stop the recursion
  2. Ground truth: Known answers to build upon
  3. Boundary handling: Edge cases at limits of subproblem space

Identifying Base Cases

Ask: "What are the smallest/simplest subproblems?"

Subproblem TypeTypical Base Cases
Prefixes x[:i]i = 0 (empty prefix)
Suffixes x[i:]i = n (empty suffix)
Substrings x[i:j]i = j (empty) or i+1 = j (single element)
Fibonacci F(i)i = 1, i = 2
Graph δ(s,v)v = s (source vertex)

Base Case Values

The value depends on what you're computing:

Problem TypeTypical Base Value
Minimization0 or ∞
Maximization0 or -∞
Counting0 or 1
BooleanTrue or False

Examples:

Fibonacci:      F(1) = F(2) = 1         (definition)
Shortest path:  δ(s,s) = 0              (zero distance to self)
Bowling:        B(n) = 0                (no pins = no score)
Counting paths: paths(s,s) = 1          (one way to stay put)

Common Mistakes with Base Cases

  1. Missing base cases: Recursion never terminates

    # BAD: What if i <= 0?
    def F(i):
        return F(i-1) + F(i-2)
  2. Wrong base case values: Incorrect final answer

    # BAD: Should be 1, not 0
    def F(i):
        if i <= 2: return 0  # Wrong!
        return F(i-1) + F(i-2)
  3. Off-by-one errors: Boundary conditions wrong

    # BAD: What about B(n-1)?
    def B(i):
        if i == n: return 0
        return max(B(i+1), v[i] + B(i+1), v[i]*v[i+1] + B(i+2))
        # Crashes when i = n-1 and we access v[i+1]

Multiple Base Cases

Sometimes you need several base cases:

# Fibonacci needs TWO base cases
def F(i):
    if i == 1: return 1
    if i == 2: return 1
    return F(i-1) + F(i-2)

# Bowling needs boundary check
def B(i):
    if i >= n: return 0  # Handles both i=n and i=n+1
    options = [B(i+1), B(i+1) + v[i]]
    if i + 1 < n:  # Can only pair if next pin exists
        options.append(B(i+2) + v[i] * v[i+1])
    return max(options)

Original Problem (O) - Deep Dive

After defining subproblems, you must specify which subproblem(s) give you the answer to the original problem you're trying to solve.

Relationship to Subproblems

PatternOriginal Problem
Original IS a subproblemReturn that subproblem directly
Original needs ALL subproblemsReturn all or aggregate them
Original needs COMBINATIONCombine multiple subproblems

Examples

Pattern 1: Original is one subproblem

Fibonacci:  Want F(n)           → Return F(n)
Bowling:    Want max score      → Return B(0) (full suffix)
LCS:        Want LCS length     → Return DP(0,0) or DP(n,m)

Pattern 2: Original needs all subproblems

DAG Shortest Paths: Want δ(s,v) for ALL v
                    → Return entire memo table

All-Pairs Shortest: Want δ(u,v) for ALL u,v
                    → Return 2D memo table

Pattern 3: Original needs combination

Longest Increasing Subsequence:
    Subproblem: LIS(i) = longest increasing subsequence ENDING at i
    Original:   max over all i of LIS(i)
                (best ending position unknown, try all)

Matrix Chain Multiplication:
    Subproblem: DP(i,j) = min cost to multiply matrices i..j
    Original:   DP(0, n-1) (multiply all matrices)

Why This Step Matters

Sometimes the subproblem definition doesn't directly give you what you want:

Problem: Find the actual longest increasing subsequence (not just length)

Subproblem: LIS(i) = length of LIS ending at index i

Original problem needs:
1. Find i* = argmax LIS(i)           # Which endpoint is best?
2. Backtrack from i* to reconstruct  # What elements are in it?

Reconstruction (Getting the Actual Solution)

DP gives you the optimal value, but often you want the optimal solution itself.

Method 1: Store parent pointers

parent = {}  # Track which choice led to optimal

def B(i):
    if i >= n: return 0
    
    skip = B(i+1)
    hit_one = B(i+1) + v[i]
    hit_two = B(i+2) + v[i]*v[i+1] if i+1 < n else float('-inf')
    
    best = max(skip, hit_one, hit_two)
    
    if best == skip:
        parent[i] = ('skip', i+1)
    elif best == hit_one:
        parent[i] = ('hit_one', i+1)
    else:
        parent[i] = ('hit_two', i+2)
    
    return best

Method 2: Backtrack through DP table

def reconstruct(i):
    if i >= n: return []
    
    skip = B[i+1]
    hit_one = B[i+1] + v[i]
    hit_two = B[i+2] + v[i]*v[i+1] if i+1 < n else float('-inf')
    
    if B[i] == skip:
        return reconstruct(i+1)
    elif B[i] == hit_one:
        return [('hit', i)] + reconstruct(i+1)
    else:
        return [('hit_pair', i, i+1)] + reconstruct(i+2)

Time Analysis (T) - Deep Dive

The final step is analyzing the running time of your DP algorithm.

The Master Formula

Time = Σ (non-recursive work for each subproblem)
     ≤ (# of subproblems) × (max work per subproblem)

This works because memoization ensures each subproblem is solved exactly once.

Breaking Down the Analysis

Step 1: Count subproblems

Subproblem TypeCount
Prefixes/SuffixesO(n)
SubstringsO(n²)
2D grid (i,j)O(nm)
Graph verticesO(V)
k parameters, each 1..nO(n^k)

Step 2: Analyze work per subproblem

Count only non-recursive work:

  • Recursive calls are "free" (counted elsewhere)
  • Count: comparisons, additions, lookups, etc.
Fibonacci:  F(i) = F(i-1) + F(i-2)
            Non-recursive work: 1 addition = O(1)

Bowling:    B(i) = max(B(i+1), B(i+1)+v[i], B(i+2)+v[i]*v[i+1])
            Non-recursive work: 2 additions, 1 multiply, 1 max = O(1)

DAG SP:     δ(s,v) = min over incoming edges of δ(s,u) + w(u,v)
            Non-recursive work: O(in-degree of v)

Step 3: Combine

Algorithm# SubproblemsWork EachTotal Time
FibonacciO(n)O(1)O(n)
BowlingO(n)O(1)O(n)
DAG Shortest PathsO(V)O(in-degree)O(V + E)
Merge Sort*O(n²)O(length)O(n³) upper bound

*Merge sort's DP analysis gives loose bound; recurrence analysis gives tight O(n log n).

When the Formula is Tight vs. Loose

Tight bound: When all subproblems do similar work

Fibonacci: Every subproblem does O(1) work
           n subproblems × O(1) = O(n) ✓ Tight

Loose bound: When work varies significantly

Merge Sort: Subproblems range from size 1 to n
            n² subproblems × O(n) = O(n³) ✗ Loose
            Actual: O(n log n) via recurrence tree

Space Complexity

Don't forget space! DP uses memory for:

  1. Memo table: O(# subproblems)
  2. Recursion stack: O(depth of recursion) for top-down
  3. Auxiliary data: Problem-specific

Space optimization: Sometimes you can reduce space:

# Fibonacci: Only need last 2 values, not all n
def fib(n):
    if n <= 2: return 1
    prev2, prev1 = 1, 1
    for i in range(3, n+1):
        curr = prev1 + prev2
        prev2, prev1 = prev1, curr
    return prev1
# Space: O(1) instead of O(n)!

Top-Down vs. Bottom-Up Comparison

AspectTop-Down (Memoization)Bottom-Up (Tabulation)
ImplementationRecursive + memo dictIterative + array
Subproblems solvedOnly those neededAll subproblems
Stack spaceO(recursion depth)O(1)
Cache performancePotentially worseBetter locality
Ease of writingOften easierRequires explicit order

Example 1: Merge Sort (Review)

Merge sort fits the SRTBOT framework:

Subproblems:    S(i,j) = sort items from index i to j-1
                For some i,j pairs

Relation:       S(i,j) = merge(S(i,m), S(m,j))
                where m = (i+j)/2

Topological:    Solve in order of increasing (j-i)

Base Case:      S(i,i) = [] (empty array)

Original:       S(0,n)

Time:           O(n log n)

Note: Merge sort doesn't benefit from memoization (no repeated subproblems).


Example 2: Fibonacci Numbers

Problem

Compute the nth Fibonacci number:

  • f_n = f_{n-1} + f_{n-2}
  • Base case: f_1 = f_2 = 1

Naive Recursive Approach

Subproblems:    F(i) = ith Fibonacci number, for i ∈ {1, ..., n}
                n subproblems

Relation:       F(i) = F(i-1) + F(i-2)

Topological:    Increasing i (for i = 1 to n)

Base Case:      F(1) = F(2) = 1

Original:       F(n)

Time:           T(n) = T(n-1) + T(n-2) + O(1)
                     ≈ φ^n (EXPONENTIAL - BAD!)

The recursion tree has massive redundancy - F(n-3) is computed multiple times.

With Memoization

Memoization: Remember and reuse solutions to subproblems.

memo = {}  # Dictionary mapping subproblems → solutions

def F(i):
    if i in memo:
        return memo[i]          # Already solved - return cached result
    if i <= 2:
        result = 1              # Base case
    else:
        result = F(i-1) + F(i-2)  # Recurrence
    memo[i] = result
    return result

Time Analysis with Memoization:

Time = Σ (non-recursive work per subproblem)
     ≤ (# subproblems) × (time per subproblem)
     = n × O(1)
     = O(n)

From exponential to linear with one simple idea!

Word RAM Consideration

For Fibonacci specifically:

  • F_n grows exponentially (~φ^n)
  • Requires Θ(n) bits to store
  • n-bit addition takes ⌈n/w⌉ time
  • True running time: O(n + n²/w)

Still polynomial vs. exponential without memoization.


The DP Formula

For any DP algorithm with memoization:

Time = Σ (non-recursive work for each subproblem)
     ≤ (# subproblems) × (max time per subproblem)

This works because:

  1. Each subproblem is solved at most once
  2. Memo table prevents recomputation
  3. Recursive calls are "free" (counted in other subproblems)

Example 3: DAG Shortest Paths

Problem

Given a DAG and source vertex s, compute shortest path weights δ(s,v) for all vertices v.

DP Formulation

Subproblems:    δ(s,v) for all v ∈ V
                |V| subproblems

Relation:       δ(s,v) = min({ δ(s,u) + w(u,v) : (u,v) ∈ E } ∪ {∞})
                (min over all incoming edges to v)

Topological:    Topological order of G (the graph IS the subproblem graph!)

Base Case:      δ(s,s) = 0

Original:       All subproblems

Time:           Σ_v |Adj⁻(v)| + 1 = O(V + E)

Key Insight

The subproblem dependency graph is the input graph G:

  • To compute δ(s,v), need δ(s,u) for all incoming neighbors u
  • Topological order of subproblems = topological order of G

Connection to DFS

The memoized recursive algorithm implicitly performs DFS:

  • Memo table = "visited" check
  • Recursion explores the reverse subproblem graph
  • Computes topological order automatically

Example 4: Bowling Problem

Problem Setup

  • n bowling pins in a line, each with value v_i (can be negative)
  • Ball can hit:
    • One pin i: Score = v_i
    • Two adjacent pins i, i+1: Score = v_i × v_{i+1}
    • Zero pins: Score = 0
  • Goal: Maximize total score

Example: pins with values [1, 1, 9, 9, 2, -5, -5]

  • Optimal: hit 1, hit 1, hit (9,9) together, skip 2, hit (-5,-5) together
  • Score: 1 + 1 + 81 + 0 + 25 = 108

Subproblem Design for Sequences

When input is a sequence x of length n:

TypeDefinitionCount
Prefixesx[:i] for all iΘ(n)
Suffixesx[i:] for all iΘ(n)
Substringsx[i:j] for all i,jΘ(n²)

NOT subsequences - there are 2^n of those (exponential)!

Prefer prefixes/suffixes (linear) over substrings (quadratic) when possible.

DP Solution

Subproblems:    B(i) = max score starting with pins i, i+1, ..., n-1
                (suffix starting at i)
                n+1 subproblems

Relation:       B(i) = max(
                    B(i+1),                      # skip pin i
                    B(i+1) + v_i,                # hit pin i alone
                    B(i+2) + v_i × v_{i+1}       # hit pins i and i+1 together
                )
                (third option only if i < n-1)

Topological:    Decreasing i (for i = n, n-1, ..., 0)

Base Case:      B(n) = 0 (no pins left)

Original:       B(0)

Time:           O(n) subproblems × O(1) work = O(n)

Bottom-Up Implementation

def bowling(v):
    n = len(v)
    B = [0] * (n + 1)  # B[n] = 0 is base case
    
    for i in range(n - 1, -1, -1):  # topological order: n-1 down to 0
        # Option 1: skip pin i
        # Option 2: hit pin i alone
        options = [B[i + 1], B[i + 1] + v[i]]
        
        # Option 3: hit pins i and i+1 together (if possible)
        if i < n - 1:
            options.append(B[i + 2] + v[i] * v[i + 1])
        
        B[i] = max(options)
    
    return B[0]  # original problem

Key DP Intuitions

Local Brute Force

DP uses local brute force:

  • For each subproblem, try ALL possible choices for one decision
  • Normally: 3 choices per pin × n pins = 3^n (exponential)
  • With DP: Reuse subproblems → O(n) total

How to Write Recurrences

  1. For suffixes: Think about the first item
  2. For prefixes: Think about the last item
  3. For substrings: Think about any item (often middle or endpoints)

The Pattern

  1. Identify a feature of the solution
  2. If you knew that feature, you could reduce to smaller subproblem
  3. Don't know which option is best? Try all options, take max/min

Summary

ConceptDescription
Dynamic ProgrammingRecursion + Memoization
SRTBOTFramework: Subproblems, Relations, Topological order, Base case, Original problem, Time
MemoizationStore and reuse computed subproblem solutions
Time FormulaTime = (# subproblems) × (work per subproblem)
Sequence SubproblemsPrefixes O(n), Suffixes O(n), Substrings O(n²)
Local Brute ForceTry all options for one decision, recurse on rest

Next Lectures

  • More DP examples with increasingly complex problems
  • When prefixes/suffixes aren't enough → substrings
  • Multiple sequences
  • More sophisticated subproblem definitions

Browse the library