








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









Those who cannot remember the past are doomed to repeat it. — George Santayana, The Life of Reason, Book I: Introduction and Reason in Common Sense (1905) If we all listened to the professor, we may be all looking for professor jobs. — Pittsburgh Steeler’s head coach Bill Cowher, responding to David Romer’s dynamic-programming analysis of football strategy (2003)
The Fibonacci numbers Fn, named after Leonardo Fibonacci Pisano^1 , the mathematician who popularized ‘algorism’ in Europe in the 13th century, are defined as follows: F 0 = 0, F 1 = 1, and Fn = Fn− 1 + Fn− 2 for all n ≥ 2. The recursive definition of Fibonacci numbers immediately gives us a recursive algorithm for computing them:
RecFibo(n): if (n < 2) return n else return RecFibo(n − 1) + RecFibo(n − 2) How long does this algorithm take? Except for the recursive calls, the entire algorithm requires only a constant number of steps: one comparison and possibly one addition. If T (n) represents the number of recursive calls to RecFibo, we have the recurrence
T (0) = 1, T (1) = 1, T (n) = T (n − 1) + T (n − 2) + 1.
This looks an awful lot like the recurrence for Fibonacci numbers! The annihilator method gives us an asymptotic bound of Θ(φn), where φ = (
5 + 1)/ 2 ≈ 1 .61803398875, the so-called golden ratio, is the largest root of the polynomial r^2 − r − 1. But it’s fairly easy to prove (hint, hint) the exact solution T (n) = 2Fn+1 − 1. In other words, computing Fn using this algorithm takes more than twice as many steps as just counting to Fn! Another way to see this is that the RecFibo is building a big binary tree of additions, with nothing but zeros and ones at the leaves. Since the eventual output is Fn, our algorithm must call RecRibo(1) (which returns 1) exactly Fn times. A quick inductive argument implies that RecFibo(0) is called exactly Fn− 1 times. Thus, the recursion tree has Fn + Fn− 1 = Fn+1 leaves, and therefore, because it’s a full binary tree, it must have 2Fn+1 − 1 nodes.
The obvious reason for the recursive algorithm’s lack of speed is that it computes the same Fibonacci numbers over and over and over. A single call to RecursiveFibo(n) results in one recursive call to RecursiveFibo(n − 1), two recursive calls to RecursiveFibo(n − 2), three recursive calls to RecursiveFibo(n − 3), five recursive calls to RecursiveFibo(n − 4), and in general, Fk− 1 recursive calls to RecursiveFibo(n − k), for any 0 ≤ k < n. For each call, we’re recomputing some Fibonacci number from scratch. We can speed up the algorithm considerably just by writing down the results of our recursive calls and looking them up again if we need them later. This process is called memoization.^2 (^1) literally, “Leonardo, son of Bonacci, of Pisa” (^2) “My name is Elmer J. Fudd, millionaire. I own a mansion and a yacht.”
MemFibo(n): if (n < 2) return n else if F [n] is undefined F [n] ← MemFibo(n − 1) + MemFibo(n − 2) return F [n]
If we actually trace through the recursive calls made by MemFibo, we find that the array F [ ] gets filled from the bottom up: first F [2], then F [3], and so on, up to F [n]. Once we realize this, we can replace the recursion with a simple for-loop that just fills up the array in that order, instead of relying on the complicated recursion to do it for us. This gives us our first explicit dynamic programming algorithm.
IterFibo(n): F [0] ← 0 F [1] ← 1 for i ← 2 to n F [i] ← F [i − 1] + F [i − 2] return F [n]
IterFibo clearly takes only O(n) time and O(n) space to compute Fn, an exponential speedup over our original recursive algorithm. We can reduce the space to O(1) by noticing that we never need more than the last two elements of the array:
IterFibo2(n): prev ← 1 curr ← 0 for i ← 1 to n next ← curr + prev prev ← curr curr ← next return curr
(This algorithm uses the non-standard but perfectly consistent base case F− 1 = 1.) But even this isn’t the fastest algorithm for computing Fibonacci numbers. There’s a faster algorithm defined in terms of matrix multiplication, using the following wonderful fact: [ 0 1 1 1
x y
y x + y
In other words, multiplying a two-dimensional vector by the matrix [ 0 11 1 ] does exactly the same thing as one iteration of the inner loop of IterFibo2. This might lead us to believe that multiplying by the matrix n times is the same as iterating the loop n times:
[ 0 1 1 1
]n [ 1 0
Fn− 1 Fn
A quick inductive argument proves this. So if we want to compute the nth Fibonacci number, all we have to do is compute the nth power of the matrix [ 0 11 1 ]. We saw in the previous lecture, and the beginning of this lecture, that computing the nth power of something requires only O(log n) multiplications. In this case, that means O(log n) 2 × 2
The edit distance between two words—sometimes also called the Levenshtein distance—is the min- imum number of letter insertions, letter deletions, and letter substitutions required to transform one word into another. For example, the edit distance between FOOD and MONEY is at most four:
FOOD → MOOD → MON∧D → MONED → MONEY
A better way to display this editing process is to place the words one above the other, with a gap in the first word for every insertion, and a gap in the second word for every deletion. Columns with two different characters correspond to substitutions. Thus, the number of editing steps is just the number of columns that don’t contain the same character twice.
F O O D M O N E Y It’s fairly obvious that you can’t get from FOOD to MONEY in three steps, so their edit distance is exactly four. Unfortunately, this is not so easy in general. Here’s a longer example, showing that the distance between ALGORITHM and ALTRUISTIC is at most six. Is this optimal?
A L G O R I T H M A L T R U I S T I C To develop a dynamic programming algorithm to compute the edit distance between two strings, we first need to develop a recursive definition. Let’s say we have an m-character string A and an n-character string B. Then define E(i, j) to be the edit distance between the first i characters of A and the first j characters of B. The edit distance between the entire strings A and B is E(m, n). This gap representation for edit sequences has a crucial “optimal substructure” property. Sup- pose we have the gap representation for the shortest edit sequence for two strings. If we remove the last column, the remaining columns must represent the shortest edit sequence for the remaining substrings. We can easily prove this by contradiction. If the substrings had a shorter edit sequence, we could just glue the last column back on and get a shorter edit sequence for the original strings. There are a couple of obvious base cases. The only way to convert the empty string into a string of j characters is by doing j insertions, and the only way to convert a string of i characters into the empty string is with i deletions:
E(i, 0) = i, E(0, j) = j.
In general, there are three possibilities for the last column in the shortest possible edit sequence:
To summarize, the edit distance E(i, j) is the smallest of these three possibilities:
E(i, j) = min
E(i − 1 , j) + 1 E(i, j − 1) + 1 E(i − 1 , j − 1) +
A[i] 6 = B[j]
[The bracket notation
denotes the indicator variable for the logical proposition P. Its value is 1 if P is true and 0 if P is false. This is the same as the C/C++/Java expression P? 1 : 0.] If we turned this recurrence directly into a recursive algorithm, we would have the following double recurrence for the running time:
T (m, n) =
O(1) if n = 0 or m = 0, T (m, n − 1) + T (m − 1 , n) + T (n − 1 , m − 1) + O(1) otherwise.
I don’t know of a general closed-form solution for this mess, but we can derive an upper bound by defining a new function
T ′(N ) = max n+m=N T (n, m) =
O(1) if N = 0, 2 T (N − 1) + T (N − 2) + O(1) otherwise.
The annihilator method implies that T ′(N ) = O((1 +
2)N^ ). Thus, our recursive edit-distance algorithm runs in time T ′(n + m) = O((1 +
2)n+m). We can bring the running time of this algorithm down to a polynomial by building an m × n table of all possible values of E(i, j). We begin by filling in the base cases, the entries in the 0th row and 0th column, each in constant time. To fill in any other entry, we need to know the values directly above it, directly to the left, and both above and to the left. If we fill in our table in the standard way—row by row from top down, each row from left to right—then whenever we reach an entry in the matrix, the entries it depends on are already available.
EditDistance(A[1 .. m], B[1 .. n]): for i ← 1 to m Edit[i, 0] ← i for j ← 1 to n Edit[0, j] ← j for i ← 1 to m for j ← 1 to n if A[i] = B[j] Edit[i, j] ← min
{ Edit[i − 1 , j] + 1, Edit[i, j − 1] + 1, Edit[i − 1 , j − 1]
} else Edit[i, j] ← min
{ Edit[i − 1 , j] + 1, Edit[i, j − 1] + 1, Edit[i − 1 , j − 1] + 1
}
return Edit[m, n]
Since there are Θ(mn) entries in the table, and each entry takes Θ(1) time once we know its predecessors, the total running time is Θ(mn). The algorithm uses O(mn) space. Here’s the resulting table for ALGORITHM → ALTRUISTIC. Bold numbers indicate places where characters in the two strings are equal. The arrows represent the predecessor(s) that actually define each entry. Each direction of arrow corresponds to a different edit operation: horizontal=deletion, vertical=insertion, and diagonal=substitution. Bold diagonal arrows indicate “free” substitutions of a letter for itself. Any path of arrows from the top left corner to the bottom right corner of this table represents an optimal edit sequence between the two strings. (There can be many such paths.) Moreover, since we can compute these arrows in a postprocessing phase from the values stored in the table, we can reconstruct the actual optimal editing sequence in O(n + m) additional time.
A simple inductive argument implies that Half(m, n) is the correct value of h. We can easily modify our earlier algorithm so that it computes Half(m, n) at the same time as the edit distance Edit(m, n), all in O(mn) time, using only O(m) space. Now, to compute the optimal editing sequence that transforms A into B, we recursively com- pute the optimal subsequences. The recursion bottoms out when one (or both) strings has only constant length, in which case we can determine the optimal editing sequence by our old dynamic programming algorithm. Overall the running time of our recursive algorithm satisfies the following recurrence:
T (m, n) =
O(n) if m ≤ 1 O(m) if n ≤ 1 O(mn) + T (m/ 2 , h) + T (m/ 2 , n − h) otherwise
It’s easy to prove inductively that T (m, n) = O(mn), no matter what values of h we get. Specifically, the entire algorithm’s running time is at most twice the time for the initial dynamic programming phase.
T (m, n) ≤ αmn + T (m/ 2 , h) + T (m/ 2 , n − h) ≤ αmn + 2αmh/2 + 2αm(n − h)/ 2 by the inductive hypothesis = 2αmn
Using a similar argument, it’s easy to show that the algorithm uses only O(n + m) space.
If we’re very very very very lucky, we can bypass all the recurrences and tables and so forth, and solve the problem using a greedy algorithm. The general greedy strategy is look for the best first step, take it, and then continue. For example, a greedy algorithm for the edit distance problem might look for the longest common substring of the two strings, match up those substrings (since those substitutions dont cost anything), and then recursively look for the edit distances between the left halves and right halves of the strings. If there is no common substring—that is, if the two strings have no characters in common—the edit distance is clearly the length of the larger string. If this sounds like a hack to you, pat yourself on the back. It isn’t even close to the correct solution. Nevertheless, for many problems involving dynamic programming, many student’s first intuition is to apply a greedy strategy. This almost never works; problems that can be solved correctly by a greedy algorithm are very rare. Everyone should tattoo the following sentence on the back of their hands, right under all the rules about logarithms and big-Oh notation:
Well... hardly ever. In the near future, we’ll see the pain and heartache required to prove that greedy algorithms are correct, in the rare instances when they are.
You all remember that the cost of a successful search in a binary search tree is proportional to the depth of the target node plus one. As a result, the worst-case search time is proportional to the
height of the tree. To minimize the worst-case search time, the height of the tree should be as small as possible; ideally, the tree is perfectly balanced. In many applications of binary search trees, it is more important to minimize the total cost of several searches than to minimize the worst-case cost of a single search. If x is a more ‘popular’ search target than y, we can save time by building a tree where the depth of x is smaller than the depth of y, even if that means increasing the overall height of the tree. A perfectly balanced tree is not the best choice if some items are significantly more popular than others. In fact, a totally unbalanced tree of depth Ω(n) might actually be the best choice! This situation suggests the following problem. Suppose we are given a sorted array of n keys A[1 .. n] and an array of corresponding access frequencies f [1 .. n]. Over the lifetime of the search tree, we will search for the key A[i] exactly f [i] times. Our task is to build the binary search tree that minimizes the total search time. Before we think about how to solve this problem, we should first come up with the right way to describe the function we are trying to optimize! Suppose we have a binary search tree T. Let depth(T, i) denote the depth of the node in T that stores the key A[i]. Up to constant factors, the total search time S(T ) is given by the following expression:
∑^ n
i=
depth(T, i) + 1
· f [i]
This expression is called the weighted external path length of T. We can trivially split this expression into two components:
S(T ) =
∑^ n
i=
f [i] +
∑^ n
i=
depth(T, i) · f [i].
The first term is the total number of searches, which doesn’t depend on our choice of tree at all. The second term is called the weighted internal path length of T. We can express S(T ) in terms of the recursive structure of T as follows. Suppose the root of T contains the key A[r], so the left subtree stores the keys A[1 .. r − 1], and the right subtree stores the keys A[r + 1 .. n]. We can actually define depth(T, i) recursively as follows:
depth(T, i) =
depth(left(T ), i) + 1 if i < r 0 if i = r depth(right(T ), i) + 1 if i > r
If we plug this recursive definition into our earlier expression for S(T ), we get the following:
∑^ n
i=
f [i] +
r∑− 1
i=
depth(left(T ), i) + 1
· f [i] +
r∑− 1
i=
depth(right(T ), i) + 1
· f [i]
This looks complicated, until we realize that the second and third look exactly like our initial expression for S(T )!
S(T ) =
∑^ n
i=
f [i] + S(left(T )) + S(right(T ))
Now our task is to compute the tree Topt that minimizes the total search time S(T ). Suppose the root of Topt stores key A[r]. The recursive definition of S(T ) immediately implies that the left subtree left(Topt) must also be the optimal search tree for the keys A[1 .. r−1] and access frequencies
ComputeS(i, j): S[i, j] ← ∞ for r ← i to j tmp ← S[i, r − 1] + S[r + 1, j] if S[i, j] > tmp S[i, j] ← tmp S[i, j] ← S[i, j] + F [i, j]
The only question left is what order to fill in the table. Each entry S[i, j] depends on all entries S[i, r − 1] and S[r + 1, j] with i ≤ k ≤ j. In other words, every entry in the table depends on all the entries directly to the left or directly below. In order to fill the table efficiently, we must choose an order that computes all those entries before S[i, j]. There are at least three different orders that satisfy this constraint. The one that occurs to most people first is to scan through the table one diagonal at a time, starting with the trivial base cases S[i, i − 1]. The complete algorithm looks like this:
OptimalSearchTree(f [1 .. n]): InitF(f [1 .. n]) for i ← 1 to n S[i, i − 1] ← 0 for d ← 0 to n − 1 for i ← 1 to n − d ComputeS(i, i + d) return S[1, n]
We could also traverse the array row by row from the bottom up, traversing each row from left to right, or column by column from left to right, traversing each columns from the bottom up. These two orders give us the following algorithms:
OptimalSearchTree2(f [1 .. n]): InitF(f [1 .. n]) for i ← n downto 1 S[i, i − 1] ← 0 for j ← i to n ComputeS(i, j) return S[1, n]
OptimalSearchTree3(f [1 .. n]): InitF(f [1 .. n]) for j ← 0 to n S[j + 1, j] ← 0 for i ← j downto 1 ComputeS(i, j) return S[1, n]
Three different orders to fill in the table S[i, j].
No matter which of these three orders we actually use, the resulting algorithm runs in Θ(n^3 ) time and uses Θ(n^2 ) space. We could have predicted this from the original recursive formulation.
S(i, j) =
0 if j = i − i F (i, j) + min i≤r≤j
S(i, r − 1) + S(r + 1, j)
otherwise
First, the function has two arguments, each of which can take on any value between 1 and n, so we probably need a table of size O(n^2 ). Next, there are three variables in the recurrence (i, j, and r), each of which can take any value between 1 and n, so it should take us O(n^3 ) time to fill the table. In general, you can get an easy estimate of the time and space bounds for any dynamic program- ming algorithm by looking at the recurrence. The time bound is determined by how many values all the variables can have, and the space bound is determined by how many values the parameters of the function can have. For example, the (completely made up) recurrence
F (i, j, k, l, m) = min 0 ≤p≤i max 0 ≤q≤j
k∑−m
r=
F (i − p, j − q, r, l − 1 , m − r)
should immediately suggest a dynamic programming algorithm to compute F (n, n, n, n, n) in O(n^8 ) time and O(n^5 ) space. This simple rule of thumb usually gives us the right time bound to shoot for.
But not always! In fact, the algorithm I’ve described is not the most efficient algorithm for comput- ing optimal binary search trees. Let R[i, j] denote the root of the optimal search tree for A[i .. j]. Donald Knuth proved the following nice monotonicity property for optimal subtrees: if we move either end of the subarray, the optimal root moves in the same direction or not at all, or more formally:
R[i, j − 1] ≤ R[i, j] ≤ R[i + 1, j] for all i and j.
This (nontrivial!) observation leads to the following more efficient algorithm:
FasterOptimalSearchTree(f [1 .. n]): InitF(f [1 .. n]) for i ← n downto 1 S[i, i − 1] ← 0 R[i, i − 1] ← i for j ← i to n ComputeSandR(i, j) return S[1, n]
ComputeSandR(f [1 .. n]): S[i, j] ← ∞ for r ← R[i, j − 1] to j tmp ← S[i, r − 1] + S[r + 1, j] if S[i, j] > tmp S[i, j] ← tmp R[i, j] ← r S[i, j] ← S[i, j] + F [i, j]
It’s not hard to see the r increases monotonically from i to n during each iteration of the outermost for loop. Consequently, the innermost for loop iterates at most n times during a single iteration of the outermost loop, so the total running time of the algorithm is O(n^2 ). If we formulate the problem slightly differently, this algorithm can be improved even further. Suppose we require the optimum external binary tree, where the keys A[1 .. n] are all stored at the leaves, and intermediate pivot values are stored at the internal nodes. An algorithm due to Te Ching Hu and Alan Tucker^3 computes the optimal binary search tree in this setting in only O(n log n) time!
(^3) T. C. Hu and A. C. Tucker, Optimal computer search trees and variable length alphabetic codes, SIAM J. Applied Math. 21:514–532, 1971. For a slightly simpler algorithm with the same running time, see A. M. Garsia and M. L. Wachs, A new algorithms for minimal binary search trees, SIAM J. Comput. 6:622–642, 1977. The original correctness proofs for both algorithms are rather intricate; for simpler proofs, see Marek Karpinski, Lawrence L. Larmore, and Wojciech Rytter, Correctness of constructing optimal alphabetic trees revisited, Theoretical Computer Science, 180:309-324, 1997.
best triangle to attach to the first and last corners, and let the recursion fairy take care of the rest:
M (i, j) =
0 if j = i + 1 min i<k<j
∆(i, j, k) + M (i, k) + M (k, j)
otherwise
What we’re looking for is M (1, n). If you think this looks similar to the recurrence for S(i, j), the cost of an optimal binary search tree, you’re absolutely right. We can build up intermediate results in a two-dimensional table, starting with the base cases M [i, i + 1] = 0 and working our way up. We can use the following algorithm fragment to compute a generic entry M [i, j]:
ComputeM(i, j): M [i, j] ← ∞ for k ← i + 1 to j − 1 tmp ← ∆(i, j, k) + M [i, k] + M [k, j] if M [i, j] > tmp M [i, j] ← tmp As in the optimal search tree problem, each table entry M [i, j] depends on all the entries directly to the left or directly below, so we can use any of the orders described earlier to fill the table.
MinTriangulation: for i ← 1 to n − 1 M [i, i + 1] ← 0 for d ← 2 to n − 1 for i ← 1 to n − d ComputeM(i, i + d) return M [1, n]
MinTriangulation2: for i ← n downto 1 M [i, i + 1] ← 0 for j ← i + 2 to n ComputeM(i, j) return M [1, n]
MinTriangulation3: for j ← 2 to n M [j − 1 , j] ← 0 for i ← j − 1 downto 1 ComputeM(i, j) return M [1, n]
In all three cases, the algorithm runs in Θ(n^3 ) time and uses Θ(n^2 ) space, just as we should have guessed from the recurrence.
Actually, the last two problems are both special cases of the same meta-problem: computing optimal Catalan structures. There is a straightforward one-to-one correspondence between the set of triangulations of a convex n-gon and the set of binary trees with n − 2 nodes. In effect, these two problems differ only in the cost function for a single node/triangle.
A polygon triangulation and the corresponding binary tree. (Squares represent null pointers.) A third problem that fits into the same mold is the infamous matrix chain multiplication problem. Using the standard algorithm, we can multiply a p × q matrix by a q × r matrix using O(pqr) arithmetic operations; the result is a p×r matrix. If we have three matrices to multiply, the cost depends on which pair we multiply first. For example, suppose A and C are 1000 × 2 matrices and B is a 2 × 1000 matrix. There are two different ways to compute the threefold product ABC:
Now suppose we are given an array D[0 .. n] as input, indicating that each matrix Mi has D[i − 1] rows and D[i] columns. We have an exponential number of possible ways to compute the n-fold product
∏n i=1 Mi. The following dynamic programming algorithm computes the number of arithmetic operations for the best possible parenthesization:
MatrixChainMult: for i ← n downto 1 M [i, i + 1] ← 0 for j ← i + 2 to n ComputeM(i, j) return M [1, n]
ComputeM(i, j): M [i, j] ← ∞ for k ← i + 1 to j − 1 tmp ← (D[i] · D[j] · D[k]) + M [i, k] + M [k, j] if M [i, j] > tmp M [i, j] ← tmp
The derivation of this algorithm is left as a simple exercise.