









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
Everyone who enjoys thinks that the principal thing to the tree is the fruit, but in point of fact the principal thing to it is the seed. — Friedrich Nietzsche
When you come to a fork in the road, take it. — Yogi Berra
Wouldn’t the sentence “I want to put a hyphen between the words Fish and And and And and Chips in my Fish-And-Chips sign.” have been clearer if quotation marks had been placed before Fish, and between Fish and and, and and and And, and And and and, and and and And, and And and and, and and and Chips, as well as after Chips?^1 — unknown, from the original FreeBSD ‘fortune’ file
Reduction is the single most common technique used in designing algorithms. Reducing one problem 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 algorithm described in Lecture 0 reduces the problem of apportioning Congress to the problem of maintaining a priority queue under the operations INSERT and EXTRACTMAX. Those data structure operations are black boxes; the apportionment algorithm does not depend on any specific implementation. Conversely, when we design a particular priority queue data structure, we typically neither know nor care how our data structure will be used. Whether or not the Census Bureau plans to use our code to apportion Congress is completely irrelevant to our design choices. As a general rule, when we design algorithms, we may not know— and we should not care —how the basic building blocks we use are implemented, or how your algorithm might be used as a basic building block to solve a bigger problem. Using reductions effectively is a difficult skill to master. For most of our educational careers, especially before high school, we are faced almost exclusively with very simple mathematics problems. A particularly powerful kind of reduction is recursion , which can be defined loosely as follows:
If the self-reference is confusing, it’s helpful 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 simpler subproblems.^2 (^1) If you ever decide to read this sentence out loud, be sure to pause briefly between ‘Fish and and’ and ‘and and and And’, ‘and and and And’ and ‘and And and and’, ‘and And and and’ and ‘and and and And’, ‘and and and And’ and ‘and And and and’, and ‘and And and and’ and ‘and and and Chips’! (^2) I used to refer to ‘elves’ instead of the Recursion Fairy, referring to the traditional fairy tale about an old shoemaker who leaves his work unfinished when he goes to bed, only to discover upon waking that elves have finished everything overnight. Someone more entheogenically experienced than I might recognize them as Terence McKenna’s ‘self-adjusting machine elves’.
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’ subproblems. Eventually, the recursive reductions must stop with an elementary base case that can be solved by some other method; otherwise, the recursive algorithm will never terminate. This finiteness condition is almost always satisfied trivially, but we should always be wary of ‘obvious’ recursive algorithms that actually recurse forever.^3
The Tower of Hanoi puzzle was first published by the mathematician François Éduoard Anatole Lucas in 1883, under the pseudonym ‘N. Claus (de Siam)’ (an anagram of ‘Lucas d’Amiens’). The following year, Henri de Parville described the puzzle with the following remarkable story:^4 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. 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 n th disk. And then after we move the n th 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... STOP!! That’s it! We’re done! We’ve successfully reduced the n -disk Tower of Hanoi problem to two instances of the ( n − 1 )-disk Tower of Hanoi problem, which we can gleefully hand off to the Recursion Fairy (or, to carry the original story further, to the junior monks at the temple). (^3) All too often, ‘obvious’ is a synonym for ‘false’. (^4) This English translation is from W. W. Rouse Ball and H. S. M. Coxeter’s book Mathematical Recreations and Essays.
the subsets { 8 , 7 } or { 7 , 5 , 3 } or { 6 , 9 } or { 5 , 10 }. 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, because the elements of the empty set add up to zero.^5 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 is a subset of X that sums to T if and only if one of the following statements is true:
In the first case, there must be a subset of X \ { x } that sums to T − x ; in the second case, there must be a subset of X \ { x } that sums to T. 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 , so TRUE is the correct output. Otherwise, if T is negative or the set X is empty, then no subset of X sums to T , so FALSE is the correct output. 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 ( 2 n ) by the annihilator method. Here is a similar recursive algorithm that actually constructs a subset of X that sums to T , if one exists. This algorithm also runs in O ( 2 n ) 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
(^5) There’s no base case like the vacuous base case!
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 as 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.^6
Now suppose we are given a sequence of integers, and we want to find the longest subsequence whose elements are in increasing order. More concretely, the input is 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.
A sequence of integers is either empty or an integer followed by a sequence of integers.
This definition suggests the following strategy for devising a recursive algorithm. If the input sequence is empty, there’s nothing to do. Otherwise, we should figure out what to do with the first element of the input sequence, and let the Recursion Fairy take care of everything else. We can formalize this strategy somewhat by giving a recursive definition of subsequence (using array notation to represent sequences):
The only subsequence of the empty sequence is the empty sequence. A subsequence of A [1 .. n ] is either a subsequence of A [2 .. n ] or A [ 1 ] followed by a subsequence of A [2 .. n ].
We’re not just looking for just any subsequence, but a longest subsequence with the property that elements are in increasing order. So let’s try to add those two conditions to our definition. (I’ll omit the familiar vacuous base case.)
The LIS of A [1 .. n ] is either the LIS of A [2 .. n ] or A [ 1 ] followed by the LIS of A [2 .. n ] with elements larger than A [ 1 ], whichever is longer.
This definition is correct, but it’s not quite recursive—we’re defining ‘longest increasing subsequence’ in terms of the different ‘longest increasing subsequence with elements larger than x ’, which we haven’t properly defined yet. Fortunately, this second object has a very similar recursive definition. (Again, I’m omitting the vacuous base case.)
If A [ 1 ] ≤ x , the LIS of A [1 .. n ] with elements larger than x is the LIS of A [2 .. n ] with elements larger than x. Otherwise, the LIS of A [1 .. n ] with elements larger than x is either the LIS of A [2 .. n ] with elements larger than x or A [ 1 ] followed by the LIS of A [2 .. n ] with elements larger than A [ 1 ], whichever is longer.
(^6) Indeed, because SUBSETSUM is NP-hard, there is almost certainly no way to solve it in subexponential time.
Since polynomial factors like n^3 are essentially noise when the overall running time is exponential, 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 ( 2 n^ poly( n )). We can make this algorithm smarter by exploiting the special recursive structure of 3CNF formulas:
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 ( 3 n^ 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 Φ′|¯ x y. Similarly, if Φ′|¯ x y 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(Φ|¯ x y ) 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 hard to prove (hint, hint) that if Φ has a satisfying assignment, then it has a satisfying assignment where every pure literal is true. If Φ = ( x ∨ y ∨ z ) ∧ Φ′^ has no pure literals, then some in Φ contains the literal ¯ x , so we can write
Φ = ( x ∨ y ∨ z ) ∧ ( x ¯ ∨ u ∨ v ) ∧ Φ′
for some literals u and v (each of which might be y , ¯ y , z , or z ¯). It follows that the first recursive formula Φ| x has contains the clause ( u ∨ v ). We can recursively eliminate the variables u and v just as we tested the variables y and x in the second and third cases of our previous algorithm:
Φ| x = ( u ∨ v ) ∧ Φ′| x = ( u ∧ Φ′| xu ) ∨ ( v ∧ Φ′| x ¯ uv ).
Here is our new faster algorithm:
3 SAT(Φ): if Φ = ∅ return TRUE if Φ has a pure literal x return 3SAT(Φ| x ) ( x ∨ y ∨ z ) ∧ ( x ¯ ∨ u ∨ v ) ∧ Φ′^ ← Φ if 3SAT(Φ| xu ) return TRUE if 3SAT(Φ| x uv ¯) return TRUE if 3SAT(Φ|¯ x y ) return TRUE return 3SAT(Φ| x ¯ ¯ yz ) The running time T ( n ) of this new algorithm satisfies the recurrence
T ( n ) = 2 T ( n − 2 ) + 2 T ( n − 3 ) + poly( n ),
and the annihilator method implies that
T ( n ) = O ( μn^ poly( n )) = O (1.76929235425 n )
where μ ≈ 1.76929235424... is the largest root of the characteristic polynomial r^3 − 2 r − 2. Naturally, this approach can be extended much further. As of 2004, the fastest (deterministic) algorithm for 3SAT runs in O ( 1. 473 n ) time^7 , but there is absolutely no reason to believe that this is the best possible.
Finally, suppose we are given an undirected graph G and are asked to find the size of the largest independent set , that is, the largest subset of the vertices of G with no edges between them. Once again, we have an obvious recursive algorithm: Try every subset of nodes, and return the largest subset with no edges. Expressed recursively, the algorithm might look like this.
(^7) Tobias Brueggemann and Walter Kern. An improved deterministic local search algorithm for 3-SAT. Theoretical Computer Science 329(1–3):303–313, 2004.
M ( n ) ≤ max
M ( n − 1 ) 2 M ( n − 2 ) M ( n − 1 ) + M ( n − 4 ) 3 M ( n − 3 )
n/ (^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 independent set in G in O ( 3 n/^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:
∑^ n i = 1
ai =
0 if n = 0 n ∑− 1 i = 1
ai + an otherwise
(b) 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,....
Here’s the non-recursive algorithm in one line:
In step i , move disk ρ ( i ) forward if n − i is even, backward if n − i is odd.
When this rule requires us to move disk n + 1, the algorithm ends.
(a) Suppose you are forbidden to move any disk directly between needle 1 and needle 2; every move must involve needle 0. Describe an algorithm to solve this version of the puzzle in as few moves as possible. Exactly how many moves does your algorithm make? (b) Suppose you are only allowed to move disks from needle 0 to needle 2, from needle 2 to needle 1, or from needle 1 to needle 0. Equivalently, Suppose the needles are arranged in a circle and numbered in clockwise order, and you are only allowed to move disks counterclockwise. Describe an algorithm to solve this version of the puzzle in as few moves as possible. Exactly how many moves does your algorithm make?
0 1 2 3 4
5 6 7 8 A top view of the first eight moves in a counterclockwise Towers of Hanoi solution ∆(c) Finally, suppose your only restriction is that you may never move a disk directly from needle 1 to needle 2. Describe an algorithm to solve this version of the puzzle in as few moves as possible. How many moves does your algorithm make? [Hint: This is considerably harder to analyze than the other two variants.]
The largest complete subtree of this binary tree has depth 2.