









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!










The first nuts and bolts appeared in the middle 1400’s. The bolts were just screws with straight sides and a blunt end. The nuts were hand-made, and very crude. When a match was found between a nut and a bolt, they were kept together until they were finally assembled. In the Industrial Revolution, it soon became obvious that threaded fasteners made it easier to assemble products, and they also meant more reliable products. But the next big step came in 1801, with Eli Whitney, the inventor of the cotton gin. The lathe had been recently improved. Batches of bolts could now be cut on different lathes, and they would all fit the same nut. Whitney set up a demonstration for President Adams, and Vice-President Jefferson. He had piles of musket parts on a table. There were 10 similar parts in each pile. He went from pile to pile, picking up a part at random. Using these completely random parts, he quickly put together a working musket. — Karl S. Kruszelnicki (‘Dr. Karl’), Karl Trek , December 1997
Dr Neumann in his Theory of Games and Economic Behavior introduces the cut-up method of random action into game and military strategy: Assume that the worst has happened and act accordingly. If your strategy is at some point determined... by random factor your opponent will gain no advantage from knowing your strategy since he cannot predict the move. The cut-up method could be used to advantage in processing scientific data. How many discoveries have been made by accident? We cannot produce accidents to order. — William S. Burroughs, "The Cut-Up Method of Brion Gysin" in The Third Mind by William S. Burroughs and Brion Gysin (1978)
Suppose we are given n nuts and n bolts of different sizes. Each nut matches exactly one bolt and vice versa. The nuts and bolts are all almost exactly the same size, so we can’t tell if one bolt is bigger than the other, or if one nut is bigger than the other. If we try to match a nut witch a bolt, however, the nut will be either too big, too small, or just right for the bolt. Our task is to match each nut to its corresponding bolt. But before we do this, let’s try to solve some simpler problems, just to get a feel for what we can and can’t do. Suppose we want to find the nut that matches a particular bolt. The obvious algorithm — test every nut until we find a match — requires exactly n − 1 tests in the worst case. We might have to check every bolt except one; if we get down the the last bolt without finding a match, we know that the last nut is the one we’re looking for.^1 Intuitively, in the ‘average’ case, this algorithm will look at approximately n/ 2 nuts. But what exactly does ‘average case’ mean?
Normally, when we talk about the running time of an algorithm, we mean the worst-case running time. This is the maximum, over all problems of a certain size, of the running time of that algorithm on that input: T worst-case( n ) = max | X |= n
On extremely rare occasions, we will also be interested in the best-case running time:
T best-case( n ) = min | X |= n
(^1) “Whenever you lose something, it’s always in the last place you look. So why not just look there first?”
The average-case running time is best defined by the expected value , over all inputs X of a certain size, of the algorithm’s running time for X :^2
T average-case( n ) = E | X |= n
| X |= n
T ( x ) · Pr[ X ].
The problem with this definition is that we rarely, if ever, know what the probability of getting any particular input X is. We could compute average-case running times by assuming a particular probability distribution—for example, every possible input is equally likely—but this assumption doesn’t describe reality very well. Most real-life data is decidedly non-random (or at least random in some unpredictable way). Instead of considering this rather questionable notion of average case running time, we will make a distinction between two kinds of algorithms: deterministic and randomized. A deterministic algorithm is one that always behaves the same way given the same input; the input completely determines the sequence of computations performed by the algorithm. Randomized algorithms, on the other hand, base their behavior not only on the input but also on several random choices. The same randomized algorithm, given the same input multiple times, may perform different computations in each invocation. This means, among other things, that the running time of a randomized algorithm on a given input is no longer fixed, but is itself a random variable. When we analyze randomized algorithms, we are typically interested in the worst-case expected running time. That is, we look at the average running time for each input, and then choose the maximum over all inputs of a certain size:
T worst-case expected( n ) = max | X |= n
It’s important to note here that we are making no assumptions about the probability distribution of possible inputs. All the randomness is inside the algorithm, where we can control it!
Let’s go back to the problem of finding the nut that matches a given bolt. Suppose we use the same algorithm as before, but at each step we choose a nut uniformly at random from the untested nuts. ‘Uniformly’ is a technical term meaning that each nut has exactly the same probability of being chosen.^3 So if there are k nuts left to test, each one will be chosen with probability 1 /k. Now what’s the expected number of comparisons we have to perform? Intuitively, it should be about n/ 2, but let’s formalize our intuition. Let T ( n ) denote the number of comparisons our algorithm uses to find a match for a single bolt out of n nuts.^4 We still have some simple base cases T ( 1 ) = 0 and T ( 2 ) = 1, but when n > 2, T ( n ) is a random variable. T ( n ) is always between 1 and n − 1; it’s actual value depends on our algorithm’s random choices. We are interested in the expected value or expectation of T ( n ), which is defined as follows: E[ T ( n )] =
n ∑− 1
k = 1
k · Pr[ T ( n ) = k ]
(^2) The notation E[ ] for expectation has nothing to do with the shift operator E used in the annihilator method for solving recurrences! (^3) This is what most people think ‘random’ means, but they’re wrong. (^4) Note that for this algorithm, the input is completely specified by the number n. Since we’re choosing the nuts to test at random, even the order in which the nuts and bolts are presented doesn’t matter. That’s why I’m using the simpler notation T ( n ) instead of T ( X ).
Here’s another possibility. Choose a pivot bolt, and test it against every nut. Then test the matching pivot nut against every other bolt. After these 2 n − 1 tests, we have one matched pair, and the remaining nuts and bolts are partitioned into two subsets: those smaller than the pivot pair and those larger than the pivot pair. Finally, recursively match up the two subsets. The worst-case number of tests made by this algorithm is given by the recurrence
T ( n ) = 2 n − 1 + max 1 ≤ k ≤ n { T ( k − 1 ) + T ( n − k )}
= 2 n − 1 + T ( n − 1 )
Along with the trivial base case T ( 0 ) = 0, this recurrence solves to
T ( n ) =
∑^ n
i = 1
( 2 n − 1 ) = n^2.
In the worst case, this algorithm tests every nut-bolt pair! We could have been a little more clever—for example, if the pivot bolt is the smallest bolt, we only need n − 1 tests to partition everything, not 2 n − 1—but cleverness doesn’t actually help that much. We still end up with about n^2 / 2 tests in the worst case. However, since this recursive algorithm looks almost exactly like quicksort, and everybody ‘knows’ that the ‘average-case’ running time of quicksort is Θ( n log n ), it seems reasonable to guess that the average number of nut-bolt comparisons is also Θ( n log n ). As we shall see shortly, if the pivot bolt is always chosen uniformly at random , this intuition is exactly right.
The second algorithm for mathing up the nuts and bolts looks exactly like quicksort. The algorithm not only matches up the nuts and bolts, but also sorts them by size. In fact, the problems of sorting and matching nuts and bolts are equivalent, in the following sense. If the bolts were sorted, we could match the nuts and bolts in O ( n log n ) time by performing a binary search with each nut. Thus, if we had an algorithm to sort the bolts in O ( n log n ) time, we would immediately have an algorithm to match the nuts and bolts, starting from scratch, in O ( n log n ) time. This process of assuming a solution to one problem and using it to solve another is called reduction —we can reduce the matching problem to the sorting problem in O ( n log n ) time. There is a reduction in the other direction, too. If the nuts and bolts were matched, we could sort them in O ( n log n ) time using, for example, merge sort. Thus, if we have an O ( n log n ) time algorithm for either sorting or matching nuts and bolts, we automatically have an O ( n log n ) time algorithm for the other problem. Unfortunately, since we aren’t allowed to directly compare two bolts or two nuts, we can’t use heapsort or mergesort to sort the nuts and bolts in O ( n log n ) worst case time. In fact, the problem of sorting nuts and bolts deterministically in O ( n log n ) time was only ‘solved’ in 1995^5 , but both the algorithms and their analysis are incredibly technical and the constant hidden in the O (·) notation is quite large. Reductions will come up again later in the course when we start talking about lower bounds and NP-completeness.
(^5) János Komlós, Yuan Ma, and Endre Szemerédi, Sorting nuts and bolts in O ( n log n ) time, SIAM J. Discrete Math 11(3):347– 372, 1998. See also Phillip G. Bradford, Matching nuts and bolts optimally, Technical Report MPI-I-95-1-025, Max-Planck-Institut für Informatik, September 1995. Bradford’s algorithm is slightly simpler.
Intuitively, we can argue that our quicksort-like algorithm will usually choose a bolt of approximately median size, and so the average numbers of tests should be O ( n log n ). We can now finally formalize this intuition. To simplify the notation slightly, I’ll write T ( n ) in place of E[ T ( n )] everywhere. Our randomized matching/sorting algorithm chooses its pivot bolt uniformly at random from the set of unmatched bolts. Since the pivot bolt is equally likely to be the smallest, second smallest, or k th smallest for any k , the expected number of tests performed by our algorithm is given by the following recurrence:
T ( n ) = 2 n − 1 + E k
T ( k − 1 ) + T ( n − k )
= 2 n − 1 +
n
∑^ n
k = 1
T ( k − 1 ) + T ( n − k )
The base case is T ( 0 ) = 0. (We can save a few tests by setting T ( 1 ) = 0 instead of 1, but the analysis will be easier if we’re a little stupid.) Yuck. At this point, we could simply guess the solution, based on the incessant rumors that quicksort runs in O ( n log n ) time in the average case, and prove our guess correct by induction. A similar inductive proof appears in [CLR, pp. 166–167], but it was removed from the new edition [CLRS]. That’s okay; nobody ever really understood that proof anyway. (See Section 8.8 below for details.) However, if we’re only interested in asymptotic bounds, we can afford to be a little conservative. What we’d really like is for the pivot bolt to be the median bolt, so that half the bolts are bigger and half the bolts are smaller. This isn’t very likely, but there is a good chance that the pivot bolt is close to the median bolt. Let’s say that a pivot bolt is good if it’s in the middle half of the final sorted set of bolts, that is, bigger than at least n/ 4 bolts and smaller than at least n/ 4 bolts. If the pivot bolt is good, then the worst split we can have is into one set of 3 n/ 4 pairs and one set of n/ 4 pairs. If the pivot bolt is bad, then our algorithm is still better than starting over from scratch. Finally, a randomly chosen pivot bolt is good with probability 1 / 2. These simple observations give us the following simple recursive upper bound for the expected running time of our algorithm:
T ( n ) ≤ 2 n − 1 +
(^3) n 4
Å (^) n
4
ã
· T ( n )
A little algebra simplifies this even further:
T ( n ) ≤ 4 n − 2 + T
(^3) n 4
Å (^) n 4
ã
We can solve this recurrence using the recursion tree method, giving us the unsurprising upper bound T ( n ) = O ( n log n ). A similar argument gives us the matching lower bound T ( n ) = Ω( n log n ). Unfortunately, while this argument is convincing, it is not a formal proof, because it relies on the unproven assumption that T ( n ) is a convex function, which means that T ( n + 1 ) + T ( n − 1 ) ≥ 2 T ( n ) for all n. T ( n ) is actually convex, but we never proved it. Convexity follows form the closed-form solution of the recurrence, but using that fact would be circular logic. Sadly, formally proving convexity seems to be almost as hard as solving the recurrence. If we want a proof of the expected cost of our algorithm, we need another way to proceed.
Since the set { Bi , Bi + 1 ,... , Bj } contains j − i + 1 bolts, each of which is equally likely to be chosen first, we immediately have
E[ Xi j ] =
j − i + 1
for all i < j.
Symmetric arguments give us E[ Xi j ] = (^) i −^2 j + 1 for all i > j. Since our algorithm is a little stupid, every bolt is compared with its partner, so Xii = 1 for all i. (In fact, if a pivot bolt is the only bolt in its subset, we don’t need to compare it against its partner, but this improvement complicates the analysis.) Putting everything together, we get the following summation.
E[ T ( n )] =
∑^ n
i = 1
∑^ n
j = 1
E[ Xi j ]
∑^ n
i = 1
E[ Xii ] + 2
∑^ n
i = 1
∑^ n
j = i + 1
E[ Xi j ]
= n + 4
∑^ n
i = 1
∑^ n
j = i + 1
j − i + 1
This is quite a bit simpler than the recurrence we got before. In fact, with just a few lines of algebra, we can turn it into an exact, closed-form expression for the expected number of comparisons.
E[ T ( n )] = n + 4
∑^ n
i = 1
n −∑ i + 1
j = 2
k
[substitute k = j − i + 1 ]
= n + 4
∑^ n
k = 2
n −∑ k + 1
i = 1
k [reorder summations]
= n + 4
∑^ n
k = 2
n − k + 1 k
= n + 4 ( n − 1 )
∑^ n
k = 2
k
∑^ n
k = 2
= n + 4 (( n + 1 )( Hn − 1 ) − ( n − 1 )) = 4 nHn − 7 n + 4 Hn
Sure enough, it’s Θ( n log n ).
If we’re feeling particularly masochistic, we can actually solve the recurrence directly, all the way to an exact closed-form solution. [I’m including this only to show you it can be done; this won’t be on the test.] First we simplify the recurrence slightly by combining symmetric terms.
T ( n ) = 2 n − 1 +
n
∑^ n
k = 1
T ( k − 1 ) + T ( n − k )
= 2 n − 1 +
n
n ∑− 1
k = 0
T ( k )
We then convert this ‘full history’ recurrence into a ‘limited history’ recurrence by shifting, and subtracting away common terms. (I call this “Magic step #1”.) To make this slightly easier, we first multiply both sides of the recurrence by n to get rid of the fractions.
nT ( n ) = 2 n^2 − n + 2
n ∑− 1
k = 0
T ( k )
( n − 1 ) T ( n − 1 ) = (^2) ︸ ( n − 1 )^2 ︷︷^ − ( n − (^1) ︸) 2 n^2 − 5 n + 3
n ∑− 2
k = 0
T ( k )
nT ( n ) − ( n − 1 ) T ( n − 1 ) = 4 n − 3 + 2 T ( n − 1 )
T ( n ) = 4 −
n
n + 1 n
T ( n − 1 )
To solve this limited-history recurrence, we define a new function t ( n ) = T ( n ) / ( n + 1 ). (I call this “Magic step #2”.) This gives us an even simpler recurrence for t ( n ) in terms of t ( n − 1 ):
t ( n ) =
T ( n ) n + 1 =
n + 1
n
T ( n − 1 ) n
n + 1
n ( n + 1 )
n + 1
n
I used the technique of partial fractions (remember calculus?) to replace (^) n ( n^1 + 1 ) with (^1) n − (^) n +^11 in the last step. The base case for this recurrence is t ( 0 ) = 0. Once again, we have a recurrence that translates directly into a summation, which we can solve with just a few lines of algebra.
t ( n ) =
∑^ n
i = 1
i + 1
i
∑^ n
i = 1
i + 1
∑^ n
i = 1
i = 7 ( Hn + 1 − 1 ) − 3 Hn
= 4 Hn − 7 +
n + 1
The last step uses the recursive definition of the harmonic numbers: Hn + 1 = Hn + (^) n +^11. Finally,
substituting T ( n ) = ( n + 1 ) t ( n ) and simplifying gives us the exact solution to the original recurrence.
T ( n ) = 4 ( n + 1 ) Hn − 7 ( n + 1 ) + 7 = 4 nHn − 7 n + 4 Hn
Surprise, surprise, we get exactly the same solution!
LIGHTTHECIRCLE( n ): k ← 0 turn on light 0 while at least one light is off with probability 1 / 2 k ← ( k + 1 ) mod n else k ← ( k − 1 ) mod n if light k is off, turn it on
(a) Let p ( i , n ) be the probability that light i is the last to be turned on by LIGHTTHECIRCLE( n , 0). For example, p ( 0 , 2 ) = 0 and p ( 1 , 2 ) = 1. Find an exact closed-form expression for p ( i , n ) in terms of n and i. Prove your answer is correct. (b) Give the tightest upper bound you can on the expected running time of this algorithm.
(a) Prove that the probability that the walk ends by falling off the right end of the path is exactly 1 / ( n + 1 ). (b) Prove that if we start at vertex k , the probability that we fall off the right end of the path is exactly k/ ( n + 1 ). (c) Prove that if we start at vertex 1, the expected number of steps before the random walk ends is exactly n. (d) Suppose we start at vertex n/ 2 instead. State and prove a tight Θ-bound on the expected length of the random walk in this case.
(a) Consider the following implementation of RANDOMPERMUTATION. RANDOMPERMUTATION( n ): for i = 1 to n π [ i ] ← NULL for i = 1 to n j ← RANDOM( n ) while ( π [ j ] != NULL) j ← RANDOM( n ) π [ j ] ← i return π Prove that this algorithm is correct. Analyze its expected runtime. (b) Consider the following partial implementation of RANDOMPERMUTATION.
RANDOMPERMUTATION( n ): for i = 1 to n A [ i ] ← RANDOM( n ) π ← SOMEFUNCTION( A ) return π Prove that if the subroutine SOMEFUNCTION is deterministic, then this algorithm cannot be correct. [Hint: There is a one-line proof.] (c) Consider a correct implementation of RANDOMPERMUTATION( n ) with the following property: whenever it calls RANDOM( k ), the argument k is at most m. Prove that this algorithm always calls RANDOM at least Ω( n log^ log m^ n ) times. (d) Describe and analyze an implementation of RANDOMPERMUTATION that runs in expected worst-case time O ( n ).
DOSOMETHINGINTERESTING(stream S ): repeat x ← next item in S 〈〈 do something fast with x 〉〉 until S ends return 〈〈 something 〉〉
Describe and analyze an algorithm that chooses one element uniformly at random from a data stream, without knowing the length of the stream in advance. Your algorithm should spend O ( 1 ) time per stream element and use O ( 1 ) space (not counting the stream itself).
RANDOMSELECT( A [1 .. n ], r ) : k ← PARTITION( A [1 .. n ], RANDOM( n )) if r < k return RANDOMSELECT( A [1 .. k − 1 ], r ) else if r > k return RANDOMSELECT( A [ k + 1 .. n ], r − k ) else return A [ k ]
(a) State a recurrence for the expected running time of RANDOMSELECT, as a function of n and r.
(a) Describe and analyze an algorithm to solve the following problem in O ( n ) time: Given indices i , j , i ′, j ′^ as input, compute the number of elements of M smaller than M [ i ][ j ] and larger than M [ i ′][ j ′]. (b) Describe and analyze an algorithm to solve the following problem in O ( n ) time: Given indices i , j , i ′, j ′^ as input, return an element of M chosen uniformly at random from the elements smaller than M [ i ][ j ] and larger than M [ i ′][ j ′]. Assume the requested range is always non-empty. (c) Describe and analyze a randomized algorithm to compute the median element of M in O ( n log n ) expected time.
i 1 2 3 4 5 6 7 8 9 X [ i ] 83 54 16 31 45 99 78 62 27 N [ i ] 6 8 9 5 2 3 1 7 4
Describe and analyze a randomized algorithm that determines whether a given number x appears in the array X in O ( p n ) expected time. Your algorithm may not modify the arrays X and N.
∨
∧ ∧ ∧ ∧ ∧ ∧ ∧ ∧
∧ ∧
∨ ∨ ∨
∨
You can decide whether it’s worth playing or not as follows. Imagine that the nodes at even levels (where it’s your turn) are OR gates, the nodes at odd levels (where it’s Death’s turn) are and gates. Each gate gets its input from its children and passes its output to its parent. White and black stand for TRUE and FALSE. If the output at the top of the tree is TRUE, then you can win and live forever! If the output at the top of the tree is FALSE, you should challenge Death to a game of Twister instead.
(a) Describe and analyze a deterministic algorithm to determine whether or not you can win. [Hint: This is easy!] (b) Unfortunately, Death won’t let you even look at every node in the tree. Describe a randomized algorithm that determines whether you can win in O ( 3 n ) expected time. [Hint: Consider the case n = 1 .]