






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!







Our life is frittered away by detail. Simplify, simplify. — Henry David Thoreau When you come to a fork in the road, take it. — Yogi Berra Ha ha! Cookies on dowels! — Phil Ken Sebben [played by Stephen Colbert] “Harvey Birdman, Attorney at Law”
Reduction is the single most common technique used in designing algorithms. Reducing one prob- lem X to another problem (or set of problems) Y means to write an algorithm for X, using an algorithm or Y as a subroutine or black box. For example, the congressional apportionment al- gorithm described in the previous lecture reduces the problem of apportioning Congress to the problem of maintaining a priority queue under the operations INSERT and EXTRACTMAX. In this class, we’ll generally treat primitive data structures like arrays, linked lists, stacks, queues, hash tables, binary search trees, and priority queues as black boxes, adding them to the basic vocabulary of our model of computation. When we design algorithms, we may not know—and we should not care—how these basic building blocks will actually be implemented. In some sense, every algorithm is simply a reduction to some underlying model of computation. Whenever you write a C program, you’re really just reducing some problem to the “simpler” prob- lems of compiling C, allocating memory, formatting output, scheduling jobs, and so forth. Even ma- chine language programs are just reductions to the hardware-implemented problems of retrieving and storing memory and performing basic arithmetic. The underlying hardware implementation reduces those problems to timed Boolean logic; low-level hardware design reduces Boolean logic to basic physical devices such as wires and transistors; and the laws of physics reduce wires and transistors to underlying mathematical principles. At least, that’s what the people who actually build hardware have to assume.^1 A particularly powerful kind of reduction is recursion , which can be defined loosely as a reduc- ing a problem to one or more simpler instances of the same problem. If the self-reference is confusing, it’s useful to imagine that someone else is going to solve the simpler problems, just as you would assume for other types of reductions. Your only task is to simplify the original problem, or to solve it directly when simplification is either unnecessary or impossible; the Recursion Fairy will magically take care of the rest.^2 There is one mild technical condition that must be satisfied in order for any recursive method to work correctly, namely, that there is no infinite sequence of reductions to ‘simpler’ and ‘simpler’
(^1) The situation is exactly analogous to that of mathematical proof. Normally, when we prove a theorem, we implicitly rely on a several earlier results. These eventually trace back to axioms, definitions, and the rules of logic, but it is extremely rare for any proof to be expanded to pure symbol manipulation. Even when proofs are written in excruciating Bourbakian formal detail, the accuracy of the proof depends on the consistency of the formal system in which the proof is written. This consistency is simply taken for granted. In some cases (for example, first-order logic and the first-order theory of the reals) it is possible to prove consistency, but this consistency proof necessarily (thanks be to G¨odel) relies on some different formal system (usually some extension of Zermelo-Fraenkel set theory), which is itself assumed to be consistent. Yes, it’s turtles all the way down. (^2) I used to refer to ‘elves’ instead of the Recursion Fairy, referring to the traditional fairy tale in which an old shoemaker repeatedly leaves his work half-finished when he goes to bed, only to discover upon waking that elves have finished his work while he slept.
subproblems. Eventually, the recursive reductions must stop with an elementary base case that is solved by some other method; otherwise, the algorithm will never terminate. This finiteness condition is usually easy to satisfy, but we should always be wary of ‘obvious’ recursive algorithms that actually recurse forever.
The Tower of Hanoi puzzle was first published by the French mathematician Franc¸ois ´Eduoard Ana- tole Lucas in 1883, under the pseudonym ‘N. Claus (de Siam)’ (an anagram of ‘Lucas d’Amiens’). The following year, the French scientist Henri de Parville described the puzzle with the following remarkable story:^3
In the great temple at Benares beneath the dome which marks the centre of the world, rests a brass plate in which are fixed three diamond needles, each a cubit high and as thick as the body of a bee. On one of these needles, at the creation, God placed sixty-four discs of pure gold, the largest disc resting on the brass plate, and the others getting smaller and smaller up to the top one. This is the Tower of Bramah. Day and night unceasingly the priests transfer the discs from one diamond needle to another according to the fixed and immutable laws of Bramah, which require that the priest on duty must not move more than one disc at a time and that he must place this disc on a needle so that there is no smaller disc below it. When the sixty-four discs shall have been thus transferred from the needle on which at the creation God placed them to one of the other needles, tower, temple, and Brahmins alike will crumble into dust, and with a thunderclap the world will vanish.
Of course, being good computer scientists, we read this story and immediately substitute n for the hardwired constant sixty-four.^4 How can we move a tower of n disks from one needle to another, using a third needles as an occasional placeholder, never placing any disk on top of a smaller disk?
The Tower of Hanoi puzzle
The trick to solving this puzzle is to think recursively. Instead of trying to solve the entire puzzle all at once, let’s concentrate on moving just the largest disk. We can’t move it at the beginning, because all the other disks are covering it; we have to move those n − 1 disks to the third needle before we can move the nth disk. And then after we move the nth disk, we have to move those n − 1 disks back on top of it. So now all we have to figure out is how to...
(^3) This English translation is from W. W. Rouse Ball and H. S. M. Coxeter’s book Mathematical Recreations and Essays. (^4) Recognizing that the underlying mathematical abstraction would be unchanged, we may also freely use ‘cookies’ and ‘dowels’ instead of ‘discs’ and ‘needles’. Ha ha... underlying!
and suppose the problem is to move n disks from needle 0 to needle 2 (as shown on the previous page). The non-recursive algorithm can be described with four simple rules. The proof that these rules force the same behavior as the recursive algorithm is a straightforward exercise in induction. (Hint, hint.)^5
An even shorter formulation ties the algorithm more closely with its analysis. Let ρ(n) denote the smallest integer k such that n/ 2 k^ is not an integer. For example, ρ(42) = 2, because 42 / 21 is an integer but 42 / 22 is not. (Equivalently, ρ(n) is one more than the position of the least significant 1 bit in the binary representation of n.) The function ρ(n) is sometimes called the ‘ruler’ function, because its behavior resembles the marks on a ruler:
1 , 2 , 1 , 3 , 1 , 2 , 1 , 4 , 1 , 2 , 1 , 3 , 1 , 2 , 1 , 5 , 1 , 2 , 1 , 3 , 1 , 2 , 1 , 4 , 1 , 2 , 1 , 3 , 1 , 2 , 1 , 6 , 1 , 2 , 1 , 3 , 1 , 2 , 1 , 4 , 1....
The Hanoi algorithm can now be described in one line:
In step i , move disk ρ(i) forward if n − i is even, backward if n − i is odd.
On move 2 n, this rule requires us to move disk n + 1, which doesn’t exist, so the algorithm ends. At this point, the puzzle is solved. Again, the proof that this algorithm is equivalent to our recursive formulation is a simple exercise in induction. (Hint, hint.)
Let’s start with a concrete example, the subset sum problem: Given a set X of positive integers and target integer T , is there a subset of element sin X that add up to T? Notice that there can be more than one such subset. For example, if X = { 8 , 6 , 7 , 5 , 3 , 10 , 9 } and T = 15, the answer is TRUE, thanks to the subset { 8 , 7 } or { 7 , 5 , 3 } or { 6 , 9 } or { 5 , 10 }.^6 On the other hand, if X = { 11 , 6 , 5 , 1 , 7 , 13 , 12 } and T = 15, the answer is FALSE. There are two trivial cases. If the target value T is zero, then we can immediately return TRUE, since the elements of the empty set add up to zero.^7 On the other hand, if T < 0 , or if T 6 = 0 but the set X is empty, then we can immediately return FALSE. For the general case, consider an arbitrary element x ∈ X. (We’ve already handled the case where X is empty.) There are two possibilities to consider.
So we can solve SUBSETSUM(X, T ) by reducing it to two simpler instances: SUBSETSUM(X \ {x}, T − x) and SUBSETSUM(X \ {x}, T ). Here’s how the resulting recusive algorithm might look if X is stored in an array.
SUBSETSUM(X[1 .. n], T ): if T = 0 return TRUE else if T < 0 or n = 0 return FALSE else return SUBSETSUM(X[2 .. n], T ) ∨ SUBSETSUM(X[2 .. n], T − X[1])
Proving this algorithm correct is a straightforward exercise in induction. If T = 0, then the elements of the empty subset sum to T. Otherwise, if T is negative or the set X is empty, then no subset of X sums to T. Otherwise, if there is a subset that sums to T , then either it contains X[1] or it doesn’t, and the Recursion Fairy correctly checks for each of those possibilities. Done. The running time T (n) clearly satisfies the recurrence T (n) ≤ 2 T (n − 1) + O(1), so the running time is T (n) = O(2n) by the annihilator method. Along similar lines, here’s a recursive algorithm for actually constructing a subset of X that sums to T , if one exists. This algorithm also runs in O(2n) time.
CONSTRUCTSUBSET(X[1 .. n], T ): if T = 0 return ∅ if T < 0 or n = 0 return NONE Y ← CONSTRUCTSUBSET(X[2 .. n], T ) if Y 6 = NONE return Y Y ← CONSTRUCTSUBSET(X[2 .. n], T − X[1]) if Y 6 = NONE return Y ∪ {X[1]} return NONE
These two algorithms are examples of a general algorithmic technique called backtracking. You can imagine the algorithm searching through a binary tree of recursive possibilities like a maze, trying to find a hidden treasure (T = 0), and backtracking whenever it reaches a dead end (T < 0 or n = 0). For some problems, there are tricks that allow the recursive algorithm to recognize some branches dead ends without exploring them directly, thereby speeding up the algorithm; two such problems are described later in these notes. Alas, SUBSETSUM is not one of the those problems; in the worst case, our algorithm explicitly considers every subset of X.
Suppose we want to find the longest increasing subsequence of a sequence of n integers. That is, we are given an array A[1 .. n] of integers, and we want to find the longest sequence of indices 1 ≤ i 1 < i 2 < · · · ik ≤ n such that A[ij ] < A[ij+1] for all j. To derive a recursive algorithm for this problem, we start with a recursive definition of the kinds of objects we’re playing with: sequences and subsequences.
The running time of this algorithm satisfies the recurrence
T (n) ≤ O(1) + 2T (n − 1),
which implies that T (n) = O(2n) by the annihilator method. We really shouldn’t be surprised by this running time; in the worst case, the algorithm examines each of the 2 n^ subsequences of the input array.
In lecture, a student suggested the following alternate strategy, which avoids defining a new object with the ‘larger than x’ constraint. We still only have to decide whether to include or exclude the first element A[1]. We consider the case where A[1] is excluded exactly the same way, but to consider the case where A[1] is included, we remove any elements of A[2 .. n] that are larger than A[1] before we recurse. This modified strategy gives us the following algorithm:
FILTER(A[1 .. n], x): j ← 1 for i ← 1 to n if A[i] > x B[j] ← A[i]; j ← j + 1 return B[1 .. j]
LIS(A[1 .. n]): if n = 0 return 0 else max ← LIS(prev, A[2 .. n]) L ← 1 + LIS(A[1], FILTER(A[2 .. n], A[1])) if L > max max ← L return max
The FILTER subroutine clearly runs in O(n) time, so the running time of LIS satisfies the recur- rence T (n) ≤ 2 T (n − 1) + O(n), which solves to T (n) ≤ O(2n) by the annihilator method. This upper bound pessimistically assumes that FILTER never actually removes any elements, but this can actually happen in the worst case, when the input sequence is sorted.
This section assumes you are already familiar with NP-completeness.
Now let’s consider the mother of all NP-hard problems, 3SAT. Given a boolean formula in conjunc- tive normal form, with at most three literals in each clause, our task is to determine whether any assignment of values of the variables makes the formula true. Yes, this problem is NP-hard, which means that a polynomial algorithm is almost certainly impossible. Too bad; we have to solve the problem anyway. The trivial solution is to try every possible assignment. We’ll evaluate the running time of our 3SAT algorithms in terms of the number of variables in the formula, so let’s call that n. Provided any clause appears in our input formula at most once—a condition that we can easily enforce in polynomial time—the overall input size is O(n^3 ). There are 2 n^ possible assignments, and we can evaluate each assignment in O(n^3 ) time, so the overall running time is O(2nn^3 ). Since polynomial factors like n^3 are essentially noise when the overall running time is expo- nential, from now on I’ll use poly(n) to represent some arbitrary polynomial in n; in other words, poly(n) = nO(1). For example, the trivial algorithm for 3SAT runs in time O(2n^ poly(n)). We can make this algorithm smarter by exploiting the special recursive structure of 3CNF for- mulas:
A 3CNF formula is either nothing or a clause with three literals ∧ a 3CNF formula
Suppose we want to decide whether some 3CNF formula Φ with n variables is satisfiable. Of course this is trivial if Φ is the empty formula, so suppose
Φ = (x ∨ y ∨ z) ∧ Φ′
for some literals x, y, z and some 3CNF formula Φ′. By distributing the ∧ across the ∨s, we can rewrite Φ as follows: Φ = (x ∧ Φ′) ∨ (y ∧ Φ′) ∨ (z ∧ Φ′)
For any boolean formula Ψ and any literal x, let Ψ|x (pronounced “sigh given eks”) denote the simpler boolean formula obtained by assuming x is true. It’s not hard to prove by induction (hint, hint) that x ∧ Ψ = x ∧ Ψ|x, which implies that
Φ = (x ∧ Φ′|x) ∨ (y ∧ Φ′|y) ∨ (z ∧ Φ′|z).
Thus, in any satisfying assignment for Φ, either x is true and Φ′|x is satisfiable, or y is true and Φ′|y is satisfiable, or z is true and Φ′|z is satisfiable. Each of the smaller formulas has at most n − 1 variables. If we recursively check all three possibilities, we get the running time recurrence
T (n) ≤ 3 T (n − 1) + poly(n),
whose solution is O(3n^ poly(n)). So we’ve actually done worse! But these three recursive cases are not mutually exclusive! If Φ′|x is not satisfiable, then x must be false in any satisfying assignment for Φ. So instead of recursively checking Φ′|y in the second step, we can check the even simpler formula Φ′|¯xy. Similarly, if Φ′|xy¯ is not satisfiable, then we know that y must be false in any satisfying assignment, so we can recursively check Φ′|x¯yz¯ in the third step.
3 SAT(Φ): if Φ = ∅ return TRUE (x ∨ y ∨ z) ∧ Φ′^ ← Φ if 3SAT(Φ|x) return TRUE if 3SAT(Φ|¯xy) return TRUE return 3SAT(Φ|¯x¯yz)
The running time off this algorithm obeys the recurrence
T (n) = T (n − 1) + T (n − 2) + T (n − 3) + poly(n),
where poly(n) denotes the polynomial time required to simplify boolean formulas, handle control flow, move stuff into and out of the recursion stack, and so on. The annihilator method gives us the solution T (n) = O(λn^ poly(n)) = O(1. 83928675522 n)
where λ ≈ 1. 83928675521... is the largest root of the characteristic polynomial r^3 − r^2 − r − 1. (Notice that we cleverly eliminated the polynomial noise by increasing the base of the exponent ever so slightly.) We can improve this algorithm further by eliminating pure literals from the formula before recursing. A literal x is pure in if it appears in the formula Φ but its negation x¯ does not. It’s not
MAXIMUMINDSETSIZE(G): if G = ∅ return 0 else v ← any node in G withv ← 1 + MAXIMUMINDSETSIZE(G \ N (v)) withoutv ← MAXIMUMINDSETSIZE(G \ {v}) return max{withv , withoutv }.
Here, N (v) denotes the neighborhood of v: the set containing v and all of its neighbors. Our algorithm is exploiting the fact that if an independent set contains v, then by definition it contains none of v’s neighbors. In the worst case, v has no neighbors, so G \ {v} = G \ N (v). Thus, the running time of this algorithm satisfies the recurrence T (n) = 2T (n − 1) + poly(n) = O(2n^ poly(n)). Surprise, surprise. This algorithm is mirroring a crude recursive upper bound for the number of maximal indepen- dent sets in a graph. If the graph is non-empty, then every maximal independent set either includes or excludes each vertex. Thus, the number of maximal independent sets satisfies the recurrence M (n) ≤ 2 M (n − 1), with base case M (1) = 1. The annihilator method gives us M (n) ≤ 2 n^ − 1. The only subset that we aren’t counting with this upper bound is the empty set! We can improve this upper bound by more carefully examining the worst case of the recurrence. If v has no neighbors, then N (v) = {v}, and both recursive calls consider a graph with n − 1 nodes. But in this case, v is in every maximal independent set, so one of the recursive calls is redundant. On the other hand, if v has at least one neighbor, then G \ N (v) has at most n − 2 nodes. So now we have the following recurrence.
M (n) ≤ max
M (n − 1) M (n − 1) + M (n − 2)
= O(1. 61803398875 n)
The upper bound is derived by solving each case separately using the annihilator method and taking the worst of the two cases. The first case gives us M (n) = O(1); the second case yields our old friends the Fibonacci numbers. We can improve this bound even more by examining the new worst case: v has exactly one neighbor w. In this case, either v or w appears in any maximal independent set. Thus, instead of recursively searching in G \ {v}, we should recursively search in G \ N (w), which has at most n − 1 nodes. On the other hand, if G has no nodes with degree 1 , then G \ N (v) has at most n − 3 nodes.
M (n) ≤ max
M (n − 1) 2 M (n − 2) M (n − 1) + M (n − 3)
= O(1. 46557123188 n)
The base of the exponent is the largest root of the characteristic polynomial r^3 − r^2 − 1. The second case implies a bound of O(
n ) = O(1. 41421356237 n), which is smaller. We can apply this improvement technique one more time. If G has a node v with degree 3 or more, then G \ N (v) has at most n − 4 nodes. Otherwise (since we have already considered nodes of degree 0 and 1 ), every node in the graph has degree 2. Let u, v, w be a path of three nodes in G (possibly with u adjacent to w). In any maximal independent set, either v is present and u, w are absent, or u is present and its two neighbors are absent, or w is present and its two neighbors are absent. In all three cases, we recursively count maximal independent sets in a graph with n − 3
nodes.
M (n) ≤ max
M (n − 1) 2 M (n − 2) M (n − 1) + M (n − 4) 3 M (n − 3)
= O(3n/^3 ) = O(1. 44224957031 n)
The third case implies a bound of O(1. 3802775691 n), where the base is the largest root of r^4 −r^3 − 1. Unfortunately, we cannot apply the same improvement trick again. A graph consisting of n/ 3 triangles (cycles of length three) has exactly 3 n/^3 maximal independent sets, so our upper bound is tight in the worst case. Now from this recurrence, we can derive an efficient algorithm to compute the largest indepen- dent set in G in O(3n/^3 poly(n)) = O(1. 44224957032 n) time.
MAXIMUMINDSETSIZE(G): if G = ∅ return 0 else if G has a node v with degree 0 return 1 + MAXIMUMINDSETSIZE(G \ {v}) 〈〈n − 1 〉〉 else if G has a node v with degree 1 w ← v’s neighbor withv ← 1 + MAXIMUMINDSETSIZE(G \ N (v)) 〈〈n − 2 〉〉 withw ← 1 + MAXIMUMINDSETSIZE(G \ N (w)) 〈〈≤ n − 2 〉〉 return max{withv , withw } else if G has a node v with degree greater than 2 withv ← 1 + MAXIMUMINDSETSIZE(G \ N (v)) 〈〈≤ n − 4 〉〉 withoutv ← MAXIMUMINDSETSIZE(G \ {v}) 〈〈≤ n − 1 〉〉 return max{withv , withoutv } else 〈〈every node in G has degree 2 〉〉 v ← any node; u, w ← v’s neighbors withu ← 1 + MAXIMUMINDSETSIZE(G \ N (u)) 〈〈≤ n − 3 〉〉 withv ← 1 + MAXIMUMINDSETSIZE(G \ N (v)) 〈〈≤ n − 3 〉〉 withw ← 1 + MAXIMUMINDSETSIZE(G \ N (w)) 〈〈≤ n − 3 〉〉 return max{withu, withv , withw }
Recursion is reduction from a problem to one or more simpler instances of the same problem. Almost every recursive algorithm (and inductive proof) closely follows a recursive definition for the object being computed. Here are a few simple recursive definitions that can be used to derive recursive algorithms: