Dynamic Programming
Recursive Algorithm Design and Dynamic Programming
Recursive Algorithm Design
An algorithm must use a fixed amount of code to handle inputs of many different sizes. Recursion expresses this idea by solving a problem in terms of smaller instances of the same problem. Loops can also express repeated work, but recursion is especially useful for designing algorithms because it makes the relationships between subproblems explicit and aligns naturally with proofs by induction.
A recursive algorithm divides the overall task into subproblems, describes how their solutions combine, and specifies an order in which they can be solved. The dependencies among subproblems can be represented as a graph:
Each vertex represents a subproblem.
A directed edge indicates that solving one subproblem requires the solution to another.
A valid computation order is a topological order of this dependency graph.
The dependency graph must be acyclic for this direct recursive process to terminate: a cycle would cause the computation to depend indefinitely on itself.
The SRTBOT Design Framework
SRTBOT is a checklist for specifying a recursive algorithm:
S — Subproblems
Define the smaller problems the algorithm will solve. A good design usually has a polynomial number of subproblems, since a method that explicitly solves exponentially many subproblems may be too slow.
The subproblem definition is often the hardest part of algorithm design. It must be rich enough to support a solution to the original problem, but limited enough to keep the number of subproblems manageable.
R — Relations
Give a recurrence or rule that computes the answer to a subproblem from the answers to smaller subproblems. The relation must make clear what choices are considered and how their results are combined.
For an optimization problem, the relation often takes a minimum or maximum over possible choices. For other kinds of problems, it may combine results using a different operation.
T — Topological order
Specify an order in which the subproblems can be computed so that every dependency is already solved when it is needed. This order can be expressed as:
A topological ordering of the subproblem dependency graph, or
A loop over subproblem parameters, such as increasing or decreasing indices.
B — Base cases
Specify the smallest subproblems that can be solved directly, without further recursive calls. Base cases prevent the recursion from continuing indefinitely.
O — Original problem
State how the original question is answered using the defined subproblems. Sometimes the original problem is itself one of the subproblems; in other cases, the algorithm must combine several subproblem results.
T — Time
Analyze the running time, accounting for both the number of subproblems and the work required for each one.
A complete recursive design identifies the subproblems, their dependencies, a valid computation order, base cases, the connection to the original problem, and the running time.
Example: Merge Sort in the SRTBOT Framework
Suppose an array A has length n. Define s(i,j) as the problem of sorting the subarray from index i up to, but not including, index j.
Subproblems and original problem
The subproblems are sorting particular subarrays. The original task is:
Relation
Choose a midpoint m between i and j. Sort each half and merge the resulting sorted arrays:
Here, merge combines two sorted arrays into one sorted array. The subarrays are smaller than the original whenever the interval has more than one element.
Topological order and base cases
Subarrays can be processed in increasing order of length, because shorter intervals must be solved before longer intervals that depend on them. An empty or one-element subarray is already sorted, so it is a base case.
This example shows how a familiar divide-and-conquer algorithm can be described using the same framework as other recursive algorithms.
Memoization: Reusing Subproblem Solutions
A basic recursive algorithm may solve the same subproblem repeatedly. Memoization avoids this repeated work by saving each computed answer and looking it up whenever that subproblem is needed again.
A memoized recursive procedure follows this pattern:
Check whether the requested subproblem is already stored in a memo table.
If so, return the stored result.
Otherwise, handle a base case or recursively solve the needed smaller subproblems.
Compute the answer, store it, and return it.
The memo table can be implemented using a dictionary, hash table, or direct-address array, depending on how subproblems are identified.
Dynamic programming combines recursive problem decomposition with memoization. Instead of recomputing a subproblem each time it appears in the recursion, the algorithm solves it once and reuses its answer.
If there are N distinct subproblems and solving each one requires Wi work apart from recursive calls, a useful running-time bound is:
The recursive calls themselves are not counted as local work in Wi; their costs are accounted for by the other terms in the sum. If there are polynomially many subproblems and each requires polynomial work, the overall running time is polynomial.
Example: Computing Fibonacci Numbers
The Fibonacci numbers are defined by:
The goal is to compute Fn.
Subproblems and relation
Define a subproblem for every index i from 1 through n: compute Fi. Its relation is:
The base cases are F1 and F2, and the original problem is to compute Fn. A valid computation order is increasing i, starting with the base cases.
Why plain recursion is slow
A direct recursive implementation calls itself to compute both Fi−1 and Fi−2. Those calls overlap: for example, computing one value may require Fi−2 directly, while another recursive branch also computes Fi−2. The same work is repeated in many parts of the recursion tree.
The running time satisfies a recurrence of the form:
This grows exponentially, approximately at the rate of the Fibonacci numbers themselves. Plain recursion is therefore inefficient for large n.
How memoization helps
With memoization, each value Fi is computed once and stored. Later requests for the same index return the stored value instead of recursively recomputing it. Since there are only n subproblems, the algorithm performs O(n) additions under a unit-cost arithmetic model.
This illustrates the central advantage of memoization: the recursion may generate many requests, but only the first request for each distinct subproblem causes that subproblem to be solved.
Arithmetic cost and bit complexity
The unit-cost arithmetic model treats each addition as constant time. Fibonacci values grow exponentially, however, so Fn requires Θ(n) bits to represent. If a machine word holds w bits, adding two values of this size takes approximately ⌈n/w⌉ word operations.
Consequently, computing all the values up to Fn requires roughly:
word operations. This remains polynomial, unlike the exponential running time of the un-memoized recursive method.
Memoization Compared with Merge Sort
Memoization can be applied to any recursive algorithm, but it is especially useful when the recursion contains overlapping subproblems.
Merge sort recursively sorts disjoint halves of an array. Its recursive calls generally do not ask for the same subarray more than once, so memoization does not meaningfully reduce its work.
If every possible interval [i,j) were treated as a merge-sort subproblem, there would be Θ(n2) intervals. Merging an interval of length j−i takes Θ(j−i) work. Summing the work across all such intervals gives a bound of Θ(n3)—a valid but poor upper bound for the ordinary merge-sort recursion.
The actual merge-sort recursion visits only the smaller set of subproblems in its divide-and-conquer tree and runs in Θ(nlogn) time. The contrast shows that an excessive or unsuitable set of subproblems can produce a weak analysis, even when it gives a polynomial bound.
Example: Shortest Paths in a Directed Acyclic Graph
Consider a directed acyclic graph with source vertex s. The goal is to find the shortest-path distance from s to every vertex.
Subproblems and original problem
For each vertex v, define a subproblem that computes the shortest-path distance from s to v, denoted δ(s,v). Solving the subproblem for every vertex solves the original problem.
Relation
If a shortest path reaches v by first reaching some predecessor u and then taking edge (u,v), its length is the distance to u plus the edge weight. Therefore:
The value ∞ represents the possibility that no path to v exists. The source has the base-case value:
Topological order and running time
The dependencies follow the graph’s edges: computing the distance to v requires distances to vertices with edges entering v. Since the graph is acyclic, its vertices have a topological order, and the subproblems can be computed in that order.
For each vertex, the recurrence examines its incoming edges. Summed over the graph, this takes O(V+E) time, where V is the number of vertices and E is the number of edges.
This is closely related to the DAG relaxation algorithm. Relaxing each incoming edge and keeping the best distance computes the same minimum as the recurrence.
Connection to depth-first search
A memoized recursive algorithm traverses the subproblem dependency graph: a larger subproblem makes recursive calls to the smaller subproblems on which it depends. Its memo table also plays a role similar to the “already visited” record in depth-first search.
For DAG shortest paths, recursive calls follow dependencies backward from a vertex to its predecessors. The recursion therefore explores the reverse direction of the dependency graph, and its completion order reflects an order suitable for solving the subproblems.
Designing Subproblems for Sequence Inputs
When the input is a sequence of length n, several common subproblem families are useful.
Prefixes
A prefix consists of the items from the beginning of the sequence through a chosen position. There are Θ(n) prefixes.
Suffixes
A suffix consists of the items from a chosen position through the end. There are Θ(n) suffixes.
Substrings
A substring consists of consecutive items from position i up to position j. There are Θ(n2) possible substrings.
Subsequences
A subsequence may omit items from the middle while preserving their order. There are 2n possible subsequences, since each item can either be included or omitted. This is usually too many to use as the full set of subproblems in a polynomial-time dynamic program.
Prefixes and suffixes are often preferable because they give only linearly many subproblems. Substrings are useful when a problem requires considering intervals of the input, despite their quadratic count.
Example: Linear Bowling
Consider n pins arranged in a line, where pin i has value vi. A throw can:
Hit one pin i, earning vi points.
Hit two adjacent pins i and i+1, earning vivi+1 points.
Once hit, pins are removed. The goal is to maximize the total score; the player is allowed to leave pins untouched.
For example, two adjacent pins valued at 9 and 9 are better hit together for 81 points than separately for 18. Two pins valued at 1 and 1 are better hit separately, yielding 2 rather than 1. Two adjacent pins valued at −5 and −5 can be worth hitting together, since their product is 25.
Subproblems and original problem
Define b(i) as the maximum score obtainable from the suffix containing pins i,i+1,…,n−1. The original problem is to maximize the score from all pins:
This definition specifies the goal of each subproblem, not just how it will be computed.
Relation
At the first pin of the suffix, there are three possibilities:
Leave pin i untouched.
Hit pin i alone.
If another pin follows, hit pins i and i+1 together.
The first two choices leave the suffix starting at i+1. The third leaves the suffix starting at i+2. Thus:
For the last pin, the pair option is unavailable, so:
The empty suffix has no pins and earns no points:
Topological order and running time
Each recurrence depends on subproblems with larger indices, which represent shorter suffixes. The valid order is therefore decreasing i, from n toward 0.
There are Θ(n) suffix subproblems, and each takes constant non-recursive work: a few additions, a multiplication, and a maximum. The running time is therefore O(n).
Top-Down and Bottom-Up Dynamic Programming
Top-down memoization
A top-down dynamic program begins with the original problem and recursively requests the subproblems it needs. It stores each answer in a memo table so that any later request for that subproblem can be answered immediately.
This approach closely follows the recursive relation and can be convenient when only some of the possible subproblems are reached.
Bottom-up dynamic programming
A bottom-up dynamic program computes subproblems iteratively in a valid topological order. For linear bowling, it first sets b(n)=0, then computes b(n−1),b(n−2),…,b(0), and finally returns b(0).
Bottom-up evaluation removes recursive-call overhead. It is especially natural when the topological order can be expressed as a simple loop and all required subproblems are known in advance.
Both approaches use the same subproblems and recurrence. They differ in how they schedule the computations.
Local Brute Force and the Design Intuition
Dynamic programming can make a search over many possible choices efficient. In the bowling problem, each pin has a small number of local choices: skip it, hit it alone, or pair it with the next pin. Trying every sequence of choices directly would create exponentially many strategies.
Instead, the recurrence examines the possible choices at the current position and combines each choice with an already defined smaller subproblem. Memoization or bottom-up evaluation ensures that each subproblem is solved only once. This pattern is called local brute force: all local options are considered, but repeated work across global strategies is shared.
The key design question is: What feature of a solution, if identified, would reduce the remaining task to a smaller subproblem? For suffix-based problems, the useful feature often concerns the first item or first few items. For prefix-based problems, it often concerns the last item. For substring-based problems, it may concern an item in the middle; removing that item can leave two smaller substrings.
Once the relevant choices are identified, an optimization recurrence usually takes a maximum when the goal is to maximize and a minimum when the goal is to minimize. The method works well when the resulting collection of subproblems is polynomial in size and each subproblem can be evaluated with polynomial work.

Ask anything
We've read this whole study set, so questions about it get the best answers.