Notes PDF
Notes PDF
Notes PDF
James Aspnes
2017-04-03 15:19
Contents
Table of contents i
Preface xv
Syllabus xvi
1 Randomized algorithms 1
1.1 A trivial example . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Verifying polynomial identities . . . . . . . . . . . . . . . . . 3
1.3 Randomized QuickSort . . . . . . . . . . . . . . . . . . . . . . 5
1.3.1 Brute force method: solve the recurrence . . . . . . . 5
1.3.2 Clever method: use linearity of expectation . . . . . . 6
1.4 Classifying randomized algorithms by their goals . . . . . . . 8
1.4.1 Las Vegas vs Monte Carlo . . . . . . . . . . . . . . . . 8
1.4.2 Randomized complexity classes . . . . . . . . . . . . . 9
1.5 Classifying randomized algorithms by their methods . . . . . 10
2 Probability theory 12
2.1 Probability spaces and events . . . . . . . . . . . . . . . . . . 13
2.1.1 General probability spaces . . . . . . . . . . . . . . . . 13
2.2 Boolean combinations of events . . . . . . . . . . . . . . . . . 15
2.3 Conditional probability . . . . . . . . . . . . . . . . . . . . . 18
i
CONTENTS ii
3 Random variables 24
3.1 Operations on random variables . . . . . . . . . . . . . . . . . 25
3.2 Random variables and events . . . . . . . . . . . . . . . . . . 25
3.3 Measurability . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Expectation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4.1 Linearity of expectation . . . . . . . . . . . . . . . . . 28
3.4.1.1 Linearity of expectation for infinite sequences 29
3.4.2 Expectation and inequalities . . . . . . . . . . . . . . 30
3.4.3 Expectation of a product . . . . . . . . . . . . . . . . 30
3.4.3.1 Walds equation (simple version) . . . . . . . 31
3.5 Conditional expectation . . . . . . . . . . . . . . . . . . . . . 33
3.5.1 Expectation conditioned on an event . . . . . . . . . . 33
3.5.2 Expectation conditioned on a random variable . . . . 34
3.5.2.1 Calculating conditional expectations . . . . . 35
3.5.2.2 The law of iterated expectation . . . . . . . . 37
3.5.2.3 Conditional expectation as orthogonal pro-
jection (optional) . . . . . . . . . . . . . . . 37
3.5.3 Expectation conditioned on a -algebra . . . . . . . . 39
3.5.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.6 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.6.1 Geometric random variables . . . . . . . . . . . . . . . 41
3.6.2 Coupon collector . . . . . . . . . . . . . . . . . . . . . 43
3.6.3 Hoares FIND . . . . . . . . . . . . . . . . . . . . . . . 44
5 Concentration bounds 54
5.1 Chebyshevs inequality . . . . . . . . . . . . . . . . . . . . . . 54
5.1.1 Computing variance . . . . . . . . . . . . . . . . . . . 55
5.1.1.1 Alternative formula . . . . . . . . . . . . . . 55
5.1.1.2 Variance of a Bernoulli random variable . . . 56
5.1.1.3 Variance of a sum . . . . . . . . . . . . . . . 56
5.1.1.4 Variance of a geometric random variable . . 57
5.1.2 More examples . . . . . . . . . . . . . . . . . . . . . . 61
5.1.2.1 Flipping coins . . . . . . . . . . . . . . . . . 61
5.1.2.2 Balls in bins . . . . . . . . . . . . . . . . . . 61
5.1.2.3 Lazy select . . . . . . . . . . . . . . . . . . . 62
5.2 Chernoff bounds . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.2.1 The classic Chernoff bound . . . . . . . . . . . . . . . 64
5.2.2 Easier variants . . . . . . . . . . . . . . . . . . . . . . 66
5.2.3 Lower bound version . . . . . . . . . . . . . . . . . . . 67
5.2.4 Two-sided version . . . . . . . . . . . . . . . . . . . . 67
5.2.5 Almost-independent variables . . . . . . . . . . . . . . 68
5.2.6 Other tail bounds for the binomial distribution . . . . 69
5.2.7 Applications . . . . . . . . . . . . . . . . . . . . . . . 69
5.2.7.1 Flipping coins . . . . . . . . . . . . . . . . . 69
5.2.7.2 Balls in bins again . . . . . . . . . . . . . . . 70
5.2.7.3 Flipping coins, central behavior . . . . . . . 70
5.2.7.4 Permutation routing on a hypercube . . . . . 71
5.3 The Azuma-Hoeffding inequality . . . . . . . . . . . . . . . . 74
5.3.1 Hoeffdings inequality . . . . . . . . . . . . . . . . . . 74
5.3.2 Azumas inequality . . . . . . . . . . . . . . . . . . . . 77
5.3.3 The method of bounded differences . . . . . . . . . . . 82
5.3.4 Applications . . . . . . . . . . . . . . . . . . . . . . . 83
5.3.4.1 Sprinkling points on a hypercube . . . . . . . 83
5.3.4.2 Chromatic number of a random graph . . . . 84
5.3.4.3 Balls in bins . . . . . . . . . . . . . . . . . . 84
5.3.4.4 Probabilistic recurrence relations . . . . . . . 85
5.3.4.5 Multi-armed bandits . . . . . . . . . . . . . . 86
CONTENTS iv
7 Hashing 104
7.1 Hash tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
7.2 Universal hash families . . . . . . . . . . . . . . . . . . . . . . 105
7.2.1 Linear congruential hashing . . . . . . . . . . . . . . . 108
7.2.2 Tabulation hashing . . . . . . . . . . . . . . . . . . . . 109
7.3 FKS hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
7.4 Cuckoo hashing . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.4.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.4.2 Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.5 Practical issues . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.6 Bloom filters . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.6.1 Construction . . . . . . . . . . . . . . . . . . . . . . . 116
7.6.2 False positives . . . . . . . . . . . . . . . . . . . . . . 117
7.6.3 Comparison to optimal space . . . . . . . . . . . . . . 119
7.6.4 Applications . . . . . . . . . . . . . . . . . . . . . . . 120
7.6.5 Counting Bloom filters . . . . . . . . . . . . . . . . . . 121
7.6.6 Count-min sketches . . . . . . . . . . . . . . . . . . . 122
7.6.6.1 Initialization and updates . . . . . . . . . . . 122
7.6.6.2 Queries . . . . . . . . . . . . . . . . . . . . . 123
7.6.6.3 Finding heavy hitters . . . . . . . . . . . . . 125
7.7 Locality-sensitive hashing . . . . . . . . . . . . . . . . . . . . 126
7.7.1 Approximate nearest neighbor search . . . . . . . . . . 126
CONTENTS v
12 Derandomization 214
12.1 Deterministic vs. randomized algorithms . . . . . . . . . . . . 215
12.2 Adlemans theorem . . . . . . . . . . . . . . . . . . . . . . . . 216
12.3 Limited independence . . . . . . . . . . . . . . . . . . . . . . 217
12.3.1 MAX CUT . . . . . . . . . . . . . . . . . . . . . . . . 217
12.4 The method of conditional probabilities . . . . . . . . . . . . 218
12.4.1 A trivial example . . . . . . . . . . . . . . . . . . . . . 219
12.4.2 Deterministic construction of Ramsey graphs . . . . . 219
12.4.3 MAX CUT using conditional probabilities . . . . . . . 220
12.4.4 Set balancing . . . . . . . . . . . . . . . . . . . . . . . 221
A Assignments 237
A.1 Assignment 1: due Sunday, 2016-09-18, at 17:00 . . . . . . . . 237
A.1.1 Bubble sort . . . . . . . . . . . . . . . . . . . . . . . . 238
A.1.2 Finding seats . . . . . . . . . . . . . . . . . . . . . . . 240
A.2 Assignment 2: due Thursday, 2016-09-29, at 23:00 . . . . . . 242
A.2.1 Technical analysis . . . . . . . . . . . . . . . . . . . . 242
A.2.2 Faulty comparisons . . . . . . . . . . . . . . . . . . . . 245
A.3 Assignment 3: due Thursday, 2016-10-13, at 23:00 . . . . . . 246
A.3.1 Painting with sprites . . . . . . . . . . . . . . . . . . . 246
A.3.2 Dynamic load balancing . . . . . . . . . . . . . . . . . 248
CONTENTS viii
Bibliography 363
Index 377
List of Figures
xii
List of Tables
xiii
List of Algorithms
xiv
Preface
These are notes for the Fall 2016 semester version of the Yale course CPSC
469/569 Randomized Algorithms. This document also incorporates the
lecture schedule and assignments, as well as some sample assignments from
previous semesters. Because this is a work in progress, it will be updated
frequently over the course of the semester.
Notes from previous versions of the course can be found at http://www.
cs.yale.edu/homes/aspnes/classes/469/notes-2014.pdf, http://www.
cs.yale.edu/homes/aspnes/classes/469/notes-2013.pdf, http://www.
cs.yale.edu/homes/aspnes/classes/469/notes-2011.pdf, and http://
www.cs.yale.edu/homes/aspnes/pinewiki/CS469(2f)2009.html. Some
sample assignments from these semesters can also be found in the appendix.
Much of the structure of the course follows the textbook, Mitzenmacher
and Upfalss Probability and Computing: Randomized Algorithms and Proba-
bilistic Analysis [MU05], with some material from Motwani and Raghavans
Randomized Algorithms [MR95]. In most cases youll find these textbooks
contain much more detail than what is presented here, so it is probably
better to consider this document a supplement to them than to treat it as
your primary source of information.
I would like to thank my many students and teaching fellows over the
years for their help in pointing out errors and omissions in earlier drafts of
these notes.
xv
Syllabus
Description
A study of randomized algorithms from several areas: graph algorithms,
algorithms in algebra, approximate counting, probabilistically checkable
proofs, and matrix algorithms. Topics include an introduction to tools from
probability theory, including some inequalities such as Chernoff bounds.
Meeting times
Monday and Wednesday 11:3512:50 in WTS A53.
Staff
The instructor for the course is James Aspnes. Office: AKW 401. Email:
[email protected]. URL: http://www.cs.yale.edu/homes/aspnes/.
The teaching fellow for the course is Lin Chen. Office: 17 Hillhouse,
Room 333. Email: [email protected]. URL: http://campuspress.yale.
edu/lchen/.
xvi
SYLLABUS xvii
Textbook
The textbook for the class is: Michael Mitzenmacher and Eli Upfal. Prob-
ability and Computing: Randomized Algorithms and Probabilistic Analysis.
Cambridge University Press, 2005. ISBN 0521835402. QA274 M574X 2005.
Course requirements
Six homework assignments (60% of the semester grade) plus a final exam
(40%).
SYLLABUS xviii
Late assignments
Late assignments will not be accepted without a Deans Excuse.
Lecture schedule
As always, the future is uncertain, so you should take parts of the schedule
that havent happened yet with a grain of salt. Readings refer to chapters or
sections in the course notes, except for those specified as in MU or MR, which
refer to the course textbook [MU05] or to the supplemental text [MR95].
Office hours, lecture times, and assignment due dates can be found at
http://www.cs.yale.edu/homes/aspnes#calendar.
xix
LECTURE SCHEDULE xx
Chain Monte Carlo sampling. Total variation distance and the cou-
pling lemma. Readings: 9.1, 9.2 up through 9.2.4; MU 7.17.2,
11.111.4.
2016-12-18 The final exam was given Sunday, December 18th, 2016, start-
ing at 14:00, in HLH17 101. It was be a closed-book test covering
all material discussed during the semester. Sample solutions are in
Appendix A.7.
Chapter 1
Randomized algorithms
1
CHAPTER 1. RANDOMIZED ALGORITHMS 2
Because this is a toy example, we assume that the dealer is not cheating.
The author is not responsible for the results of applying the analysis below
to real-world games where this assumption does not hold.
A deterministic algorithm tries the cards in some fixed order. A clever
dealer will place the Queen in the last place we look: so the worst-case payoff
is a loss of a dollar.
In the average case, if we assume that all three positions are equally likely
to hold the target card, then we turn over one card a third of the time, two
cards a third of the time, and all three cards a third of the time; this gives
an expected payoff of
1
(1 + 2 + 3) 2 = 0.
3
But this requires making assumptions about the distribution of the cards,
and we are no longer doing worst-case analysis.
The trick to randomized algorithms is that we can can obtain the same
expected payoff even in the worst case by supplying the randomness ourselves.
If we turn over cards in a random order, then the same analysis for the
average case tells us we get the same expected payoff of 0but unlike the
average case, we get this expected performance no matter where the dealer
places the cards.
1 n1
X
T (n) = (T (k) + T (n 1 k)) . (1.3.1)
n k=0
Why? Because there are n equally-likely choices for our pivot (hence the
1/n), and for each choice the expected cost is T (k) + T (n 1 k), where k
is the number of elements that land in A1 . Formally, we are using here the
law of total probability, which says that for any random variable X and
partition of the probability space into events B1 . . . Bn , then
X
E [X] = Bi E [X | Bi ] ,
where
1 X
E [X | Bi ] = X()
Pr [Bi ] B
i
CHAPTER 1. RANDOMIZED ALGORITHMS 6
1 n1
X
T (n) = (n 1) + (T (k) + T (n 1 k))
n k=0
2 n1
X
= (n 1) + T (k)
n k=0
2 n1
X
= (n 1) + T (k)
n k=1
2 n1
X
(n 1) + ak log k
n k=1
Z n
2
(n 1) + ak log k
n k=1
!
2a n2 log n n2 1
= (n 1) + +
n 2 4 4
!
2a n2 log n n2 1
= (n 1) + +
n 2 4 4
an a
= (n 1) + an log n + .
2 2n
If we squint carefully at this recurrence for a while we notice that setting
a = 2 makes this less than or equal to an log n, since the remaining terms
become (n 1) n + 1/n = 1/n 1, which is negative for n 1. We can
thus confidently conclude that T (n) 2n log n (for n 1).
actual algorithm. Pretend that we are always sorting the numbers 1 . . . n and
define for each pair of elements i < j the indicator variable Xij to be 1 if
i is compared to j at some point during the execution of the algorithm and 0
otherwise. Amazingly, we can actually compute the probability of this event
(and thus E [Xij ]): the only time i and j are compared is if one of them is
chosen as a pivot before they are split up into different arrays. How do they
get split up into different arrays? This happens if some intermediate element
k is chosen as pivot first, that is, if some k with i < k < j appears in the
permutation before both i and j. Occurrences of other elements dont affect
the outcome, so we can concentrate on the restriction of the permutations
to just the numbers i through j, and we win if this restricted permutation
starts with either i or j. This event occurs with probability 2/(j i + 1), so
we have E [Xij ] = 2/(j i + 1). Summing over all pairs i < j gives:
X X
E Xij = E [Xij ]
i<j i<j
X 2
=
i<j
ji+1
X ni+1
n1 X 2
=
i=1 k=2
k
n Xi
X 2
=
i=2 k=2
k
n
X 2(n k + 1)
=
k=2
k
n
2(n + 1)
X
= 2
k=2
k
n
X 2(n + 1)
= 2(n 1)
k=2
k
= 2(n + 1)(Hn 1) 2(n 1)
= 2(n + 1)Hn 4n.
A Las Vegas algorithm fails with some probability, but we can tell
when it fails. In particular, we can run it again until it succeeds, which
means that we can eventually succeed with probability 1 (but with a
potentially unbounded running time). Alternatively, we can think of a
Las Vegas algorithm as an algorithm that runs for an unpredictable
amount of time but always succeeds (we can convert such an algorithm
back into one that runs in bounded time by declaring that it fails if it
runs too longa condition we can detect). QuickSort is an example of
a Las Vegas algorithm.
The heuristic for remembering which class is which is that the names
were chosen to appeal to English speakers: in Las Vegas, the dealer can tell
you whether youve won or lost, but in Monte Carlo, le croupier ne parle que
Franais, so you have no idea what hes saying.
Generally, we prefer Las Vegas algorithms, because we like knowing
when we have succeeded. But sometimes we have to settle for Monte Carlo
algorithms, which can still be useful if we can get the probability of failure
small enough. For example, any time we try to estimate an average by
sampling (say, inputs to a function we are trying to integrate or political
views of voters we are trying to win over) we are running a Monte Carlo
algorithm: there is always some possibility that our sample is badly non-
representative, but we cant tell if we got a bad sample unless we already
know the answer we are looking for.
The class co-R consists of all languages L for which a poly-time Turing
machine M exists such that if x 6 L, then Pr [M (x, r) = 1] 1/2 and
if x L, then Pr [M (x, r) = 1] = 0. This is the randomized analog of
co-NP.
Probability theory
12
CHAPTER 2. PROBABILITY THEORY 13
2. Pr [] = 1.
CHAPTER 2. PROBABILITY THEORY 14
Its not hard to see that the discrete probability spaces defined in the
preceding section satisfy these axioms.
General probability spaces arise in randomized algorithms when we have
an algorithm that might consume an unbounded number of random bits.
The problem now is that an outcome consists of countable sequence of bits,
and there are uncountably many such outcomes. The solution is to consider
as measurable events only those sets with the property that membership
in them can be determined after a finite amount of time. Formally, the
probability space the set {0, 1}N of all sequences of 0 and 1 values indexed
by the natural numbers, and the measurable sets F are all sets that can be
generated by countable unions1 cylinder sets, where a cylinder set consists
of all extensions xy of some finite prefix x. The probability measure itself is
obtained by assigning the set of all points that start with x the probability
2|x| , and computing the probabilities of other sets from the axioms. 2
An oddity that arises in general probability spaces is it may be that every
particular outcome has probability zero but their union has probability 1.
For example, the probability of any particular infinite string of bits is 0, but
the set containing all such strings is the entire space and has probability
1. This is where the fact that probabilities only add over countable unions
comes in.
Most randomized algorithms books gloss over general probability spaces,
with three good reasons. The first is that if we truncate an algorithm after
a finite number of steps, we are usually get back to a discrete probability
space, which avoids a lot of worrying about measurability and convergence.
The second is that we are often implicitly working in a probability space that
is either discrete or well-understood (like the space of bit-vectors described
above). The last is that the Kolmogorov extension theorem says that
if we specify Pr [A1 A2 Ak ] consistently for all finite sets of events
1
As well as complements and countable intersections. However, it is not hard to show
that that sets defined using these operations can be reduced to mere countable unions of
cylinder sets.
2
This turns out to give the same probabilities as if we consider each outcome as a
real number in the interval [0, 1] and use Lebesgue measure to compute the probability of
events. For some applications, thinking of our random values as real numbers (or even
sequences of real numbers) can make things easier: consider for example what happens
when we want to choose one of three outcomes with equal probability.
CHAPTER 2. PROBABILITY THEORY 15
{A1 . . . Ak }, then there exists some probability space that makes these prob-
abilities work, even if we have uncountably many such events. So its usually
enough to specify how the events we care about interact, without worrying
about the details of the underlying space.
Lemma 2.2.1.
h i
Pr A = 1 Pr [A] .
For example, if our probability space consists of the six outcomes of a fair
i and A = [outcome is 3] with Pr [A] = 5/6, then Pr [outcome is not 3] =
diehroll,
Pr A = 1 1/6 = 5/6. Though this example is trivial, using the formula
does save us from having to add up the five cases where we dont get 3.
If we want to know the probability of A B, we need to know more
about the relationship between A and B. For example, it could be that
A and B are both events representing a fair coin coming up heads, with
Pr [A] = Pr [B] = 1/2. The probability of A B could be anywhere between
1/2 and 0:
For ordinary fair coins, wed expect that half the time that A happens,
B also happens. This gives Pr [A B] = (1/2) (1/2) = 1/4. To
make this formal, we might define our probability space as having
four outcomes HH, HT, TH, and TT, each of which occurs with equal
probability.
But maybe A and B represent the same fair coin: then A B = A and
Pr [A B] = Pr [A] = 1/2.
3
Countable need not be infinite, so 2 is countable.
CHAPTER 2. PROBABILITY THEORY 16
At the other extreme, maybe A and B represent two fair coins welded
together so that if one comes up heads the other comes up tails. Now
Pr [A B] = 0.
The difference between the nice case where Pr [A B] = 1/4 and the
other, more annoying cases where it doesnt is that in the first case we have
assumed that A and B are independent, which is defined to mean that
Pr [A B] = Pr [A] Pr [B].
In the real world, we expect events to be independent if they refer to
parts of the universe that are not causally related: if we flip two coins that
arent glued together somehow, then we assume that the outcomes of the
coins are independent. But we can also get independence from events that
are not causally disconnected in this way. An example would be if we rolled
a fair four-sided die labeled HH, HT, TH, TT, where we take the first letter
as representing A and the second as B.
Theres no simple formula for Pr [A B] when A and B are not disjoint,
even for independent events, but we can compute the probability by splitting
up into smaller, disjoint events and using countable additivity:
h i
(A B)
Pr [A B] = Pr (A B) (A B)
h i h i
+ Pr A B
= Pr [A B] + Pr A B
h i h i
= Pr [A B] + Pr A B + Pr A B + Pr [A B] Pr [A B]
= Pr [A] + Pr [B] Pr [A B] .
BT with T 6= .
That the right-hand side gives the probability of this event is a sneaky con-
sequence of the binomial theorem, and in particular the fact that ni=1 (1)i =
P
Pn i n
i=0 (1) 1 = (1 1) 1 is zero if n > 0 and 1 if n = 0. Using this
fact after rewriting the right-hand side using the BT events gives
" #
|S|+1
(1)|S|+1
X \ X X
(1) Pr Ai = Pr [BT ]
S{1...n},S6= iS S{1...n},S6= T S]
(1)|S|+1
X X
= Pr [BT ]
T {1...n} ST,S6=
n
!!
X X
i |T |
= Pr [BT ] (1)
T {1...n} i=1
i
Pr [BT ] ((1 1)|T | 1)
X
=
T {1...n}
Pr [BT ] (1 0|T | )
X
=
T {1...n}
X
= Pr [BT ]
T {1...n},T 6=
" n #
\
= Pr Ai .
i=1
CHAPTER 2. PROBABILITY THEORY 18
then
which is the law of total probability. Note that the last step works for
each term only if Pr [A | Bi ] is well-defined, meaning that Pr [Bi ] 6= 0. But
any such case contributes nothing to the previous sum, so we get the correct
answer if we simply omit any terms h from
ithe sum for which Pr [Bi ] = 0.
A special case arises when Pr A B = 0, which occurs, for example,
if A B. Then we just have Pr [A] = Pr [A | B] Pr [B]. If we consider an
event A = A1 A2 Ak , then we can iterate this expansion to get
Pr [W | Ai ] = Pr [B0 B1 Bi | Ai ]
= Pr [B0 B1 Bi ]
= Pr [B0 ] + Pr [B1 ] + + Pr [Bi ]
i
X
= (1/2)i
j=0
1 (1/2)i+1
= (1/2)
1 1/2
= 1 (1/2)i+1 . (2.3.5)
The clean form of this expression suggests strongly that there is a better
way to get it, and that this way involves taking the negation of the intersection
of i + 1 independent events that occur with probability 1/2 each. With a
little reflection, we can see that the probability that your objects dont fit in
my buffer is exactly (1/2)i+1
From the law of total probability (2.3.3),
X
Pr [W ] = (1 (1/2)i+1 )(1/2)i+1
i=0
X
=1 (1/4)i+1
i=0
1
=1 11 1/4
4
= 2/3.
hH, Ti and hT, Ti cause me to win, while the case hT, Hi causes me to
lose, and each case occurs with equal probability conditioned on Ci (which
excludes hH, Hi). So I win 2/3 of the time conditioned on Ci , and summing
Pr [W ] =
P
i=0 (2/3) Pr [Ci ] = 2/3 since Pr [Ci ] sums to 1, because the union
of these events includes the entire space except for the probability-zero event
C .
Still another approach is to compute the probability that our runs have
exactly the same length ( i 2i = 1/3), and argue by symmetry that
P
i=1 2
the remaining 2/3 probability is equally split between my run being longer
(1/3) and your run being longer (1/3). Since W occurs if my run is just as
long or longer, Pr[W ] = 1/3 + 1/3 = 2/3. A nice property of this approach is
that the only summation involved is over disjoint events, so we get to avoid
using conditional probability entirely.
Proof. Let (S, T ) be a min cut of size k. Then the degree of each vertex v
is at least k (otherwise (v, G v) would be a smaller cut), and G contains
4
Unlike ordinary graphs, multigraphs can have more than one edge between two vertices.
CHAPTER 2. PROBABILITY THEORY 22
This tells us what happens when we are considering a particular min cut.
If the graph has more than one min cut, this only makes our life easier. Note
that since each min cut turns up with probability at least 1/ n2 , there cant
n
be more than 2 of them.5 But even if there is only one, we have a good
chance of finding it if we simply re-run the algorithm substantially more
than n2 times.
Random variables
24
CHAPTER 3. RANDOM VARIABLES 25
S Probability
2 1/36
3 2/36
4 3/36
5 4/36
6 5/36
7 6/36
8 5/36
9 4/36
10 3/36
11 2/36
12 1/36
Table 3.1: Probability mass function for the sum of two independent fair
six-sided dice
CHAPTER 3. RANDOM VARIABLES 27
We will often refer to the probability mass function as giving the distri-
bution or joint distribution of a random variable or collection of random
variables, even though distribution (for real-valued variables) technically
refers to the cumulative distribution function F (x) = Pr [X x], which
is generally not directly computable from the probability mass function for
continuous random variables that take on uncountably many values. To
the extent that we can, we will try to avoid continuous random variables,
and the rather messy integration theory needed to handle them.
Two or more random variables are independent if all sets of events
involving different random variables are independent. In terms of proba-
bility mass functions, X and Y are independent if Pr [X = x Y = y] =
Pr [X = x] Pr [Y = y]. In terms of cumulative distribution functions, X and
Y are independent if Pr [X = x Y = y] = Pr [X = x] Pr [Y = y]. As with
events, we generally assume that random variables associated with causally
disconnected processes are independent, but this is not the only way we
might have independence.
Its not hard to see that the individual die values X and Y in our
two-dice example are independent, because every possible combination of
values x and y has the same probability 1/36 = Pr [X = x] Pr [Y = y]. If we
chose a different probability distribution on the space, we might not have
independence.
3.3 Measurability
For discrete probability spaces, any function on outcomes can be a random
variable. The reason is that any event in a discrete probability space has
a well-defined probability. For more general spaces, in order to be useful,
events involving a random variable should have well-defined probabilities.
For discrete random variables that take on only countably many values
(e.g., integers or rationals), its enough for the event [X = x] (that is, the
set { | X() = x}) to be in F for all x. For real-valued random variables,
we ask that the event [X x] be in F. In these cases, we say that X is
measurable with respect to F, or just measurable F. More exotic random
variables use a definition of measurability that generalizes the real-valued
version, which we probably wont need.3 Since we usually just assume that
3
The general version is that if X takes on values on another measure space (0 , F 0 ),
then the inverse image X 1 (A) = { | X() A} of any set A in F 0 is in F. This
means in particular that Pr maps through X to give a probability measure on 0 by
Pr0 [A] = Pr [X 1 (A)], and the condition on X 1 (A) being in F makes this work.
CHAPTER 3. RANDOM VARIABLES 28
all of our random variables are measurable unless we are doing something
funny with F to represent ignorance, this issue wont come up much.
3.4 Expectation
The expectation or expected value of a random variable X is given by
P
E [X] = x x Pr [X = x]. This is essentially an average value of X weighted
by probability, and it only makes sense if X takes on values that can be
summed in this way (e.g., real or complex values, or vectors in a real- or
complex-valued vector space). Even if the expectation makes sense, it may
be that a particular random variable X doesnt have an expectation, because
the sum fails to converge.
For example,
P6 ifX and Y are independent fair six-sided dice, then E [X] =
E [Y ] = i=1 i 16 = 21 7
6 = 2 , while E [X + Y ] is the rather horrific
12
X 2 1 + 3 2 + 4 3 + 5 4 + 6 5 + 7 6 + 8 5 + 9 4 + 10 3 + 11 2 + 12 1
i Pr [X + Y = i] =
i=2
36
252
= = 7.
36
7 7
The fact that 7 = 2 + 2 here is not a coincidence.
= a E [X] + b E [Y ] .
Note that this proof does not require that X and Y be independent. The
sum of two fair six-sided dice always has expectation 72 + 72 = 7, whether
they are independent dice, the same die counted twice, or one die X and its
complement 7 X.
Linearity of expectation makes it easy to compute the expectations of
random variables that are expressed as sums of other random variables.
One example that will come up a lot is a binomial random variable,
which is the sum S = ni=1 Xi , where each Xi is an independent, identically
P
which is the k-th term in the binomial expansion of (p + q)n . (In addition,
each Xi individually is called a Bernoulli random variable.4 ) In this case
each Xi has E [Xi ] = p, so E [S] is just np. It is possible to calculate this
fact directly from (3.4.1), but its a lot more work.
(The claim continues to hold even in more general cases, but the proof is
more work.)
One special case of this that comes up a lot is that X 0 implies
E [X] 0.
straightforward:
XX
E [XY ] = xy Pr [X = x, Y = y]
x y
XX
= xy Pr [X = x] Pr [Y = y]
x y
! !
X X
= x Pr [X = x] Pr [Y = y]
x y
= E [X] E [Y ] .
For example, the expectation of the product of two independent fair
2
six-sided dice is 27 = 49 4 .
This is not true for arbitrary random variables. If we compute the
expectation of the product of a single fair six-sided die with itself, we get
11+22+33+44+55+66
6 = 91
6 which is much larger.
The difference E [XY ] E [X] E [Y ] is called the covariance of X and
Y , written Cov [X, Y ]. It will come back later when we look at concentration
bounds in Chapter 5.
For general Xi we have to stop here. But if we also know that the Xi all
have the same expectation , then E [Xi ] doesnt depend on i and we can
bring it out of the sum. This gives
n
X h i n
X h i
E [Xi ] E 1[N i] = E 1[N i]
i=1 i=1
= E [N ] . (3.4.3)
E [X | Y ] () = E [X | Y = Y ()] . (3.5.4)
This is just another way of saying what we said already: if you want to know
what the expectation of X is conditioned on Y when you get outcome ,
find the value of Y at and condition on seeing that.
Here is a simple example. Suppose that X and Y are independent fair
coin-flips that take on the values 0 and 1 with equal probability. Then our
probability space has four elements, and looks like this:
h0, 0i h0, 1i
h1, 0i h1, 1i
This is what we see if we know the exact value of both coin-flips (or at
least the exact value of Z).
But now suppose we only know X, and want to compute E [Z] X. When
X = 0, E [Z] X = 0 = 12 0 + 12 1 = 12 ; and when X = 1, E [Z] X = 1 =
1 1 3
2 1 + 2 2 = 2 . So drawing E [Z] X over our probability space gives
1 1
2 2
3 3
2 2
Weve averaged the value of Z across each row, since each row corresponds
to one of the possible values of X.
If instead we compute E [Z] Y , we get this picture instead:
1 3
2 2
1 3
2 2
E [AX + BY | Z] = A E [X | Z] + B E [Y | Z] . (3.5.5)
= A(z) E [X | Z = z] + B(z) E [Y | Z = z] ,
E [Z | X] = E [X + Y | X]
= E [X | X] + E [Y | X]
= X + E [Y ]
1
=X+ .
2
Similarly, E [Z | Y ] = E [X + Y | Y ] = 12 + Y .
In some cases we have enough additional information to run this in
reverse. If we know Z and want to estimate X, we can use the fact that
X and Y are symmetric to argue that E [X | Z] = E [Y | Z]. But then
Z = E [X + Y | Z] = 2 E [X | Z], so E [X | Z] = Z/2. Note that this works
in general only if the events [X = a, Y = b] and [X = b, Y = a] have the
same probabilities for all a and b even if we condition on Z, which in this
case follows from the fact that X and Y are independent and identically
distributed and that addition is commutative. Other cases may be messier.8
Other facts, like X Y implies E [X | Z] E [Y | Z], can be proved
using similar techniques.
8
An example with X and Y i.d. but not independent is to imagine that we roll a
six-sided die to get X, and let Y = X + 1 if X < 6 and Y = 1 if X = 6. Now knowing
Z = X + Y = 3 tells me that X = 1 and Y = 2 exactly, neither of which is Z/2.
CHAPTER 3. RANDOM VARIABLES 37
E [X] = E [E [X | Y ]] . (3.5.6)
= E [X] .
The trick here is that we use (3.5.3) to expand out the original expression in
terms of the events Ay , then notice that E [X | Y ] is equal to E [X | Y = y]
whenever Y = y.
So as claimed, conditioning on a variable gives a way to write averaging
over cases very compactly.
Its also not too hard to show that iterated expectation works with partial
conditioning:
E [E [X | Y, Z] | Y ] = E [X | Y ] . (3.5.7)
and the fact that E [X] is an orthogonal projection of X means that E [X]
is precisely the constant value that minimizes the distance E (X )2 .
We wont actually use any of these facts in the following, but having another
way to look at conditional expectation may be helpful in understanding how
it works.
CHAPTER 3. RANDOM VARIABLES 39
3.5.4 Examples
Let X be the value of a six-sided die. Let A be the event that X is
even. Then
X
E [X | A] = x Pr [X = x | A]
x
1
= (2 + 4 + 6)
3
= 4.
3.6 Applications
3.6.1 Geometric random variables
Suppose that we are running a Las Vegas algorithm that takes a fixed
amount of time T , but succeeds only with probability p (which we take to
be independent of the outcome of any other run of the algorithm). If the
algorithm fails, we run it again. How long does it take on average to get the
algorithm to work?
We can reduce the problem to computing E [T X] = T E [X], where X
is the number of times the algorithm runs. The probability that X = n is
exactly (1p)n1 p, because we need to get n1 failures with probability 1p
each followed by a single success with probability p, and by assumption all of
these probabilities are independent. A variable with this kind of distribution
is called a geometric random variable. We saw a special case of this
distribution earlier (2.3.1.1) when we were looking at how long it took to
get a tails out of a fair coin (in that case, p was 1/2).
Using conditional expectation, its straightforward to compute E [X]. Let
A be the event that the algorithm succeeds on the first run, i.e., then event
[X = 1]. Then
h i h i
E [X] = E [X | A] Pr [A] + E X A Pr A
h i
= 1 p + E X A (1 p).
h i
The tricky part here is to evaluate E X A . Intuitively, if we dont succeed
the first time, weve wasted one step and are back where we started, so it
CHAPTER 3. RANDOM VARIABLES 42
X Y Z =X +Y E [X] E [X | Y = 3] E [X | Y ] E [Z | X] E [X | Z] E [X | X]
(1, 1) 1 1 2 7/2 7/2 7/2 1 + 7/2 2/2 1
(1, 2) 1 2 3 7/2 7/2 7/2 1 + 7/2 3/2 1
(1, 3) 1 3 4 7/2 7/2 7/2 1 + 7/2 4/2 1
(1, 4) 1 4 5 7/2 7/2 7/2 1 + 7/2 5/2 1
(1, 5) 1 5 6 7/2 7/2 7/2 1 + 7/2 6/2 1
(1, 6) 1 6 7 7/2 7/2 7/2 1 + 7/2 7/2 1
(2, 1) 2 1 3 7/2 7/2 7/2 2 + 7/2 3/2 2
(2, 2) 2 2 4 7/2 7/2 7/2 2 + 7/2 4/2 2
(2, 3) 2 3 5 7/2 7/2 7/2 2 + 7/2 5/2 2
(2, 4) 2 4 6 7/2 7/2 7/2 2 + 7/2 6/2 2
(2, 5) 2 5 7 7/2 7/2 7/2 2 + 7/2 7/2 2
(2, 6) 2 6 8 7/2 7/2 7/2 2 + 7/2 8/2 2
(3, 1) 3 1 4 7/2 7/2 7/2 3 + 7/2 4/2 3
(3, 2) 3 2 5 7/2 7/2 7/2 3 + 7/2 5/2 3
(3, 3) 3 3 6 7/2 7/2 7/2 3 + 7/2 6/2 3
(3, 4) 3 4 7 7/2 7/2 7/2 3 + 7/2 7/2 3
(3, 5) 3 5 8 7/2 7/2 7/2 3 + 7/2 8/2 3
(3, 6) 3 6 9 7/2 7/2 7/2 3 + 7/2 9/2 3
(4, 1) 4 1 5 7/2 7/2 7/2 4 + 7/2 5/2 4
(4, 2) 4 2 6 7/2 7/2 7/2 4 + 7/2 6/2 4
(4, 3) 4 3 7 7/2 7/2 7/2 4 + 7/2 7/2 4
(4, 4) 4 4 8 7/2 7/2 7/2 4 + 7/2 8/2 4
(4, 5) 4 5 9 7/2 7/2 7/2 4 + 7/2 9/2 4
(4, 6) 4 6 10 7/2 7/2 7/2 4 + 7/2 10/2 4
(5, 1) 5 1 6 7/2 7/2 7/2 5 + 7/2 6/2 5
(5, 2) 5 2 7 7/2 7/2 7/2 5 + 7/2 7/2 5
(5, 3) 5 3 8 7/2 7/2 7/2 5 + 7/2 8/2 5
(5, 4) 5 4 9 7/2 7/2 7/2 5 + 7/2 9/2 5
(5, 5) 5 5 10 7/2 7/2 7/2 5 + 7/2 10/2 5
(5, 6) 5 6 11 7/2 7/2 7/2 5 + 7/2 11/2 5
(6, 1) 6 1 7 7/2 7/2 7/2 6 + 7/2 7/2 6
(6, 2) 6 2 8 7/2 7/2 7/2 6 + 7/2 8/2 6
(6, 3) 6 3 9 7/2 7/2 7/2 6 + 7/2 9/2 6
(6, 4) 6 4 10 7/2 7/2 7/2 6 + 7/2 10/2 6
(6, 5) 6 5 11 7/2 7/2 7/2 6 + 7/2 11/2 6
(6, 6) 6 6 12 7/2 7/2 7/2 6 + 7/2 12/2 6
we can calculate this out formally (no sensible person would ever do this):
h i
X
E XA = n Pr [X = n | X 6= 1]
n=1
X Pr [X = n]
= n
n=2
Pr [X 6= 1]
X (1 p)n1 p
= n
n=2
1p
X
= n(1 p)n2 p
n=2
X
= (n + 1)(1 p)n1 p
n=1
X
=1+ n(1 p)n1 p
n=1
= 1 + E [X] .
integer values.
So we get
n/2 + n 1 n/2 + n
E [Y ] Pr [X > n X + 1] + Pr [n X + 1 X]
2 2
3 1 3
= n Pr [X > n X + 1] + n Pr [n X + 1 X]
4 2 4
3
n.
4
Now let Xi be the number of survivors after i pivot steps. Note that
max(0, Xi 1) gives the number of comparisons at the following pivot step,
so that
P
i=0 Xi is an upper bound on the number of comparisons.
We have X0 = n, and from the preceding argument E [X1 ] (3/4)n. But
more generally, we can use the same argument to show that E [Xi+1 | Xi ]
(3/4)Xi , and by induction E [Xi ] (3/4)i n. We also have that Xj = 0 for
all j n, because we lose at least one element (the pivot) at each pivoting
step. This saves us from having to deal with an infinite sum.
Using linearity of expectation,
" # " n #
X X
E Xi = E Xi
i=0 i=0
n
X
= E [Xi ]
i=0
Xn
(3/4)i n
i=0
4n.
Chapter 4
Basic probabilistic
inequalities
Here were going to look at some inequalities useful for proving properties
of randomized algorithms. These come in two flavors: inequalities involving
probabilities, which are useful for bounding the probability that something
bad happens, and inequalities involving expectations, which are used to
bound expected running times. Later, in Chapter 5, well be doing both,
by looking at inequalities that show that a random variable is close to its
expectation with high probability.
The typical use of the union bound is to show that if an algorithm can
fail only if various improbable events occur, then the probability of failure is
no greater than the sum of the probabilities of these events. This reduces
the problem of showing that an algorithm works with probability 1 to
constructing an error budget that divides the probability of failure among
all the bad outcomes.
46
CHAPTER 4. BASIC PROBABILISTIC INEQUALITIES 47
4.1.1 Applications
(See also the proof of Adlemans Theorem in Chapter 12.)
vertex is marked is then (n/2/ m)/n = 1/2 m, and the probability that
both endpoints of an edge are marked is (1/2 m) ((n/2/ m 1)/n <
1/(2 m))2 = 1/4m. So the probability that at least one of the edges has
two marked endpoints is at most m/4m = 1/4. We thus have a randomized
algorithm that outputs a set of size 2nm on average that is an independent
set with probability 3/4, without looking at any of the edges.
To see how this compares with more sensible algorithms, note that for
a graph with maximum degree , we can construct and independent set
n
of size +1 deterministically by marking some vertex, deleting all of its
neighbors, and repeating until we run out of vertices. qThe randomized
algorithm produces an independent set of size 2nnd = 2 n
in this case,
which is much worse.
E [X]
Pr [X ] . (4.2.1)
The proof is immediate from the law of total probability (2.3.3). We have
4.2.1 Applications
4.2.1.1 The union bound
Combining Markovs inequality with linearity of expectation and indicator
variables gives a succinct proof of the union bound:
h[ i hX i
Pr Ai = Pr 1Ai 1
hX i
E 1Ai
X
= E [1Ai ]
X
= Pr [Ai ] .
Note that for this to work for infinitely many events we need to use the fact
that 1Ai is always non-negative.
4.3.0.1 Proof
Here is a proof for the case that f is convex and differentiable. The idea is
that if f is convex, then it lies above the tangent line at E [X]. So we can
define a linear function g that represents this tangent line, and get, for all x:
f (x)
E [f (X)]
g(x)
f (E [X])
E [X]
But then
E [f (X)] E [g(X)]
= E f (E [X]) + (X E [X])f 0 (E [X])
4.3.1 Applications
4.3.1.1 Fair coins: lower bound
Suppose we flip n fair coins, and we want to get a lower bound on E X 2 ,
2
Heres how: The probability generating function for X is F (z) = E z k =
z k Pr [X = k] = 2n (1 + z)n . Then zF 0 (z) = 2n nz(1 + z)n1 = kz k Pr [X = k].
P P
k
CHAPTER 4. BASIC PROBABILISTIC INEQUALITIES 52
4.3.1.3 Sifters
Heres an example of Jensens inequality in action in the analysis of an actual
distributed algorithm. For some problems in distributed computing, its
useful to reduce coordinating a large number of processes to coordinating
a smaller number. A sifter [AA11] is a randomized mechanism for an
asynchronous shared-memory system that sorts the processes into winners
and losers, guaranteeing that there is at least one winner. The goal is to
make the expected number of winners as small as possible. The problem
is tricky, because processes can only communicate by reading and writing
shared variables, and an adversary gets to choose which processes participate
and fix the schedule of when each of these processes perform their operations.
The current best known sifter is due to Giakkoupis and Woelfel [GW12].
For n processes, it uses an array A of dlg ne bits, each of which can be read
or written by any of the processes. When a process executes the sifter, it
chooses a random index r 1 . . . dlg ne with probability 2r1 (this doesnt
exactly sum to 1, so the excess probability gets added to r = dlg ne). The
process then writes a 1 to A[r] and reads A[r + 1]. If it sees a 0 in its read
(or chooses r = dlg ne), it wins; otherwise it loses.
This works as a sifter, because no matter how many processes participate,
some process chooses a value of r at least as large as any other processs
value, and this process wins. To bound the expected number of winners, take
the sum over all r over the random variable Wr representing the winners
who chose this particular value r. A process that chooses r wins if it carries
Taking the
Pderivative of this a second time gives 2n n(1 + z)n1 + 2n n(n 1)z(1
+
n2 2 k1 2
z) = k
k z Pr [X = k]. Evaluate this monstrosity at z = 1 to get E X =
2
k2 Pr [X = k] = 2n n2n1 + 2n n(n 1)2n2 = n/2 + n(n 1)/4 = 2n+n4 n =
P
k
2
n /4 + n/4. This is pretty close to the lower bound we got out of Jensens inequality, but
we cant count on this happening in general.
CHAPTER 4. BASIC PROBABILISTIC INEQUALITIES 53
out its read operation before any process writes r + 1. If the adversary wants
to maximize the number of winners, it should let each process read as soon
as possible; this effectively means that a process that choose r wins if no
process previously chooses r + 1. Since r is twice as likely to be chosen as
r + 1, conditioning on a process picking r or r + 1, there is only a 1/3 chance
that it chooses r + 1. So at most 1/(1/3) 1 = 2 = O(1) process on average
choose r before some process chooses r + 1. (A simpler argument shows that
the expected number of processes that win because they choose r = dlg ne is
at most 2 as well.)
Summing Wr 2 over all r gives at most 2dlg ne winners on average.
Furthermore, if k < n processes participate, essentially the same analysis
shows that only 2dlg ke processes win on average. So this is a pretty effective
tool for getting rid of excess processes.
But it gets better. Suppose that we take the winners of one sifter and
feed them into a second sifter. Let Xk be the number of processes left after
k sifters. We have that X0 = n and E [X1 ] 2dlg ne, but what can we
say about E [X2 ]? We can calculate E [X2 ] = E [E [X2 | X1 ]] 2dlg X1 e.
Unfortunately, the ceiling means that 2dlg xe is not a concave function,
but f (x) = 2(lg x + 1) 2dlg xe is. So E [X2 ] f (f (n)), and in general
E [Xi ] f (i) (n), where f (i) is the i-fold composition of f . All the extra
constants obscure what is going on a bit, but with a little bit of algebra it is
not too hard to show that f (i) (n) = O(1) for i = O(log n).3 So this gets rid
of all but a constant number of processes very quickly.
3
The log function counts how many times you need to hit n with lg to reduce it to
one or less. So log 1 = 0, log 2 = 1, log 4 = 2, log 16 = 3, log 65536 = 4, log 265536 = 5,
and after that it starts getting silly.
Chapter 5
Concentration bounds
If we really want to get tight bounds on a random variable X, the trick will
turn out to be picking some non-negative function f (X) where (a) we can
calculate E [f (X)], and (b) f grows fast enough that merely large values of
X produce huge values of f (X), allowing us to get small probability bounds
by applying Markovs inequality to f (X). This approach is often used to
show that X lies close to E [X] with reasonably high probability, what is
known as a concentration bound.
Typically concentration bounds are applied to sums of random variables,
which may or may not be fully independent. Which bound you may want to
use often depends on the structure of your sum. A quick summary of the
bounds in this chapter is given in Table 5.1. The rule of thumb is to use
Chernoff bounds (5.2) if you have a sum of independent 01 random variables;
the Azuma-Hoeffding inequality (5.3) if you have bounded variables with a
more complicated distribution that may be less independent; and Chebyshevs
inequality (5.1) if nothing else works but you can somehow compute the
variance of your sum (e.g., if the Xi are independent or have easily computed
covariance). In the case of Chernoff bounds, you will almost always end up
using one of the weaker but cleaner versions in 5.2.2 rather than the general
version in 5.2.1.
54
CHAPTER 5. CONCENTRATION BOUNDS 55
E[S]
e
Chernoff Xi {0, 1}, independent Pr [S (1 + ) E [S]] (1+)1+
t2
Azuma-Hoeffding |Xi | ci , martingale Pr [S t] exp 2 P c2i
Var[S]
Chebyshev Pr [|S E [S]| ] 2
P
Table 5.1: Concentration bounds for S = Xi (strongest to weakest)
This formula is easier to use if you are estimating the variance from a
P 2 P 2
sequence of samples; by tracking xi and xi , you can estimate E X
and E [X] in a single pass, without having to estimate E [X] first and then go
back for a second pass to calculate (xi E [X])2 for each sample. We wont
use this particular application much, but this explains why the formula is
popular with statisticians.
For any two random variables X and Y , the quantity E [XY ]E [X] E [Y ]
is called the covariance of X and Y , written Cov [X, Y ]. If we take the
covariance of a variable and itself, covariance becomes variance: Cov [X, X] =
Var [X].
CHAPTER 5. CONCENTRATION BOUNDS 57
Note that Cov [X, Y ] = 0 when X and Y are independent; this makes
Chebyshevs inequality particularly useful for pairwise-independent ran-
dom variables, because then we can just sum up the variances of the individual
variables.
P
A typical application is when we have a sum S = Xi of non-negative
random variables with small covariance; here applying Chebyshevs inequality
to S can often be used to show that S is not likely to be much smaller than
E [S], which can be handy if we want to show that some lower bound holds
on S with some probability. This complements Markovs inequality, which
can only be used to get upper bounds.
Pn
For example, suppose S = i=1 Xi , where the Xi are independent
Bernoulli random variables with E [Xi ] = p for all i. Then E [S] = np, and
P
Var [S] = i Var [Xi ] = npq (because the Xi are independent). Chebyshevs
inequality then says
npq
Pr [|S E [S]| ] 2 .
The highest variance is when p = 1/2. In this case, he probability that
S is more than n away from its expected value n/2 is bounded by 41 2 .
Well see better bounds on this problem later, but this may already be good
enough for many purposes.
More generally, the approach of bounding S from below by estimating
E [S] and either E S 2 or Var [S] is known as the second-moment method.
that once we have flipped one coin the wrong way, we are back where
we started, except that now we have to add that extra coin to X. More
Pr[X 2 =n] n1
formally, we have, for n > 1, Pr X 2 = n X > 1 = Pr[X>1] = q q p =
1p q
Var [X] = 2
= 2. (5.1.6)
p p
By itself, this doesnt give very good bounds on X. For example, if we
CHAPTER 5. CONCENTRATION BOUNDS 59
Since 1q 1, we could have gotten this bound with a lot less work.
The other direction is not much better. We can easily calculate that
Pr [X n] is exactly q n1 (because this corresponds to flipping n coins
the wrong way, no matter what happens with subsequent coins). Using
Chebyshevs inequality gives
1 1
Pr [X n] Pr X n
p p
q/p2
2
n p1
q
= .
(np 1)2
This at least has the advantage of dropping below 1 when n gets large
enough, but its only polynomial in n while the true value is exponential.
Where this might be useful is in analyzing the sum of a bunch of geometric
random variables, as occurs in the Coupon Collector problem discussed in
3.6.2.1 Letting Xi be the number of balls to take us from i 1 to i empty
bins, we have previously argued that Xi has a geometric distribution with
1
We are following here a similar analysis in [MU05, 3.3.1].
CHAPTER 5. CONCENTRATION BOUNDS 60
ni1
p= n , so
, 2
i1 ni1
Var [Xi ] =
n n
i1
=n ,
(n i 1)2
and
" n # n
X X
Var Xi = Var [Xi ]
i=1 i=1
n
X i1
= n .
i=1 (n i 1)2
Having the numerator go up while the denominator goes down makes
this a rather unpleasant sum to try to solve directly. So we will follow the
lead of Mitzenmacher and Upfal and bound the numerator by n, giving
" n # n
X X n
Var Xi n
i=1 i=1 (n i 1)2
n
X 1
= n2
i=1
i2
X 1
n2
i=1
i2
2
= n2 .
6
2
The fact that 1
P
i=1 i2 converges to 6 is not trivial to prove, and was first
shown by Leonhard Euler in 1735 some ninety years after the question was
first proposed.2 But its easy to show that the series converges to something,
so even if we didnt have Eulers help, wed know that the variance is O(n2 ).
Since the expected value of the sum is (n log n), this tells us that we
are likely to see a total waiting time reasonably close to this; with at least
constant probability, it will be within (n) of the expectation. In fact, the
distribution is much more sharply concentrated (see [MU05, 5.4.1] or [MR95,
3.6.3]), but this bound at least gives us something.
2
See http://en.wikipedia.org/wiki/Basel_Problem for a history, or Eulers original
paper [Eul68], available at http://eulerarchive.maa.org/docs/originals/E352.pdf,
for the actual proof in the full glory of its original 18th-century typesetting. Curiously,
though Euler announced his result in 1735, he didnt submit the journal version until 1749,
and it didnt see print until 1768. Things moved more slowly in those days.
CHAPTER 5. CONCENTRATION BOUNDS 61
or more balls in a particular bin is at most (m/n m/n2 )/k 2 < m/nk 2 , and
applying the union bound, the probability that we get k + m/n or more balls
in any of the n bins is less than m/k 2 . Setting this equal to andpsolving for
k gives a probability of at most of getting more than m/n + m/ balls
in any of the bins. This is not as good a bound as we will be able to prove
later, but its at least non-trivial.
CHAPTER 5. CONCENTRATION BOUNDS 62
2. Use our sample to find an interval that is likely to contain S(k) . The
idea is to pick indices ` = (k n3/4 )n1/4 and r = (k + n3/4 )n1/4 and
use R(`) and R(r) as endpoints (we are omitting some floors and maxes
here to simplify the notation; for a more rigorous presentation see
[MR95]). The hope is that the interval P = [R(`) , R(r)] in S will both
contain S(k) , and be small, with |P | 4n3/4 + 2. We can compute the
elements of P in 2n comparisons exactly by comparing every element
with both R(`) and R(r) .
Now lets look at the probability that P misses S(k) because R(`) is too
big, where ` = kn1/4 n. This is
h i h i
Pr R(`) > S(k) = Pr X < kn1/4 n
n1/4 /4.
3
The history of this example is that Motwani and Raghavan adapted this algorithm
from a similar algorithm by Floyd and Rivest [FR75]. Mitzenmacher and Upfal give a
version that also includes the adaptations appearing Motwani and Raghavan, although
they dont say where they got it from, and it may be that both textbook versions come
from a common folklore source.
CHAPTER 5. CONCENTRATION BOUNDS 63
(with the caveat that we are being sloppy about round-off errors).
Similarly,
h i h i
Pr R(h) < S(k) = Pr X > kn1/4 + n
n1/4 /4.
Y h i
= E eXi
i
Y
= pi e + (1 pi )e0
i
Y
= (pi e + 1 pi )
i
Y
= (1 + (e 1) pi )
i
Y 1)p
e(e i
i
P
(e 1) i pi
=e
1)
= e(e .
The sneaky inequality step in the middle uses the fact that (1 + x) ex
for all x, which itself is one of the most useful inequalities you can memorize.5
Whats nice about this derivation is that at the end, the pi have vanished.
We dont care what random variables we started with or how many of them
there were, but only about their expected sumh. i
Now that we have an upper bound on E eS , we can throw it into
5
For a proof of this inequality, observe that the function f (x) = ex (1 + x) has the
derivative ex 1, which is positive for x > 0 and negative for x < 0. It follows that x = 1
is the unique minimum of f , at which f (1) = 0.
CHAPTER 5. CONCENTRATION BOUNDS 65
For 0 1.81,
2 /3
Pr [X (1 + )] e . (5.2.2)
(The actual upper limit is slightly higher.) Useful for small val-
ues of , especially because the bound can be inverted: ifpwe want
Pr [X (1 + )] exp( 2 /3) , we can use any with 3 ln(1/)/
1.81. The essential idea to the proof is to show that, in the given
range, e /(1 + )1+ exp( 2 /3). This is easiest to do numerically;
a somewhat more formal argument that the bound holds in the range
0 1 can be found in [MU05, Theorem 4.4].
For 0 4.11,
2 /4
Pr [X (1 + )] e . (5.2.3)
Pr [X R] 2R . (5.2.4)
Figure 5.1 shows the relation between the various bounds, in the region
where they cross each other.
CHAPTER 5. CONCENTRATION BOUNDS 67
2R/
4.11+
e
(1+)(1+)
1.81+ R/ 4.32
2 /4
e
2 /3 e
for 0 1.81.
Suppose that weqwant this bound to be less than . Then we need
2
2e /3 or 3 ln(2/)
. Setting to exactly this quantity, (5.2.7)
CHAPTER 5. CONCENTRATION BOUNDS 68
becomes q
Pr |S | 3 ln(2/) , (5.2.8)
provided 2e/3 .
For asymptotic purposes, we can omit the constants, giving
Proof. Rather than repeat the argument for independent variables, we will
employ a coupling, where we replace the Xi with independent Yi so that
Pn Pn
i=1 Yi gives a bound an i=1 Xi .
For the upper bound, let each Yi = 1 with independent probability
pi . Use the following process to generate a new Xi0 in increasing order
of i: if Yi = 0, set Xi0 = 0. Otherwise set Xi0 = 1 with probability
Pr Xi = 1 X1 = X10 , . . . Xi1
0 /pi , Then Xi0 Yi , and
It follows that the Xi0 have the same joint distribution as the Xi , and so
" n # " n #
Xi0
X X
Pr (1 + ) = Pr Xi (1 + )
i=1 i=1
" n #
X
Pr Yi (1 + )
i=1
!
e
.
(1 + )1+
For the other direction, generate the Xi first and generate the Yi using
the same rejection sampling trick. Now the Yi are independent (because
their joint distribution is) and each Yi is a lower bound on the corresponding
Xi .
The lemma is stated for the general Chernoff bounds (5.2.1) and (5.2.5),
but the easier versions follow from these, so they hold as well, as long as we
are careful to remember that the in the upper bound is not necessarily the
same as in the lower bound.
5.2.7 Applications
5.2.7.1 Flipping coins
Suppose S is the sum of n independent fair coin-flips. Then E [S] = n/2 and
Pr [S = n] = Pr [S 2 E [S]] is bounded using (5.2.1) by setting = n/2,
= 1 to get Pr [S = n] (e/4)n/2 = (2/ e)n . This is not quite as good as
the real answer 2n (the quantity 2/ e is about 1.213. . . ), but its at least
exponentially small.
CHAPTER 5. CONCENTRATION BOUNDS 70
110 111
010 011
100 101
000 001
q
The actual excess over the mean is (n/2) = (n/2) 6c ln n/n = 32 cn ln n.
p
the n edges leaving a processor.6 How do we route the packets so that all of
them arrive in the minimum amount of time?
We could try to be smart about this, or we could use randomization.
Valiants idea is to first route each process is packet to some random
intermediate destination (i), then in the second phase, we route it from (i)
to its ultimate destination (i). Unlike , is not necessarily a permutation;
instead, (i) is chosen uniformly at random independently of all the other
(j). This makes the choice of paths for different packets independent of
each other, which we will need later to apply Chernoff bounds..
Routing is done by a bit-fixing: if a packet is currently at node x and
heading for node y, find the leftmost bit j where xj = 6 yj and fix it, by
sending the packet on to x[xj /yj ]. In the absence of contention, bit-fixing
routes a packet to its destination in at most n steps. The hope is that the
randomization will tend to spread the packets evenly across the network,
reducing the contention for edges enough that the actual time will not be
much more than this.
The first step is to argue that, during the first phase, any particular
packet is delayed at most one time unit by any other packet whose path
overlaps with it. Suppose packet i is delayed by contention on some edge uv.
Then there must be some other packet j that crosses uv during this phase.
From this point on, j remains one step ahead of i (until its path diverges),
so it cant block i again unless both are blocked by some third packet k (in
which case we charge is further delay to k). This means that we can bound
the delays for packet i by counting how many other packets cross its path.7
So now we just need a high-probability bound on the number of packets that
get in a particular packets way.
Following the presentation in [MR95], define Hij to be the indicator
variable for the event that packets i and j cross paths during the first phase.
Because each j chooses its destination independently, once we fix is path,
P
the Hij are all independent. So we can bound S = j6=i Hij using Chernoff
bounds. To do so, we must first calculate an upper bound on = E [S].
The trick here is to observe that any path that crosses is path must cross
one of its edges, and we can bound the number of such paths by bounding
how many paths cross each edge. For each edge e, let Te be the number
of paths that cross edge e, and for each j, let Xj be the number of edges
P P
that path j crosses. Counting two ways, we have e Te = j Xj , and so
6
Formally, we have a synchronous routing model with unbounded buffers at each node,
with a maximum capacity of one packet per edge per round.
7
A much more formal version of this argument is given as [MR95, Lemma 4.5].
CHAPTER 5. CONCENTRATION BOUNDS 73
hP i
Xj N (n/2). By symmetry, all the Te have the same
P
E[ e Te ] =E j
expectation, so we get E [Te ] N N
(n/2)
n = 1/2.
Now fix (i). This determines some path e1 e2 . . . ek for packet i. In
general we do not expect E [Te` | (i)] to equal E [Te` ], because conditioning
on is path crossing e` guarantees that at least one path crosses this edge that
might not have. However, if we let Te0 be the number of packets j 6= i that
cross e, then we have Te0 Te always, giving E [Te0 ] E [Te ], and because Te0
does not depend on is path, E [Te0 | (i)] = E [Te0 ] E [Te ] 1/2. Summing
this bound over all k n edges on is path gives E [Hij | (i)] n/2, which
implies E [Hij ] n/2 after removing the conditioning on (i).
Inequality (5.2.4) says that Pr [X R] 2R when R 2e. Letting
X = j6=i Hij and setting R = 3n gives R = 6(n/2) 6 > 2e, so
P
hP i
3n = N 3 . This says that any one packet reaches its
Pr j Hij 3n 2
random destination with at most 3n added delay (thus, in at most 4n time
units) with probability at least 1 N 3 . If we consider all N packets, the
total probability that any of them fail to reach their random destinations in
4n time units is at most N N 3 = N 2 . Note that because we are using
the union bound, we dont need independence for this stepwhich is good,
because we dont have it.
What about the second phase? Here, routing the packets from the random
destinations back to the real destinations is just the reverse of routing them
from the real destinations to the random destinations. So the same bound
applies, and with probability at most N 2 some packet takes more than
4n time units to get back (this assumes that we hold all the packets before
sending them back out, so there are no collisions between packets from
different phases).
Adding up the failure probabilities and costs for both stages gives a
probability of at most 2/N 2 that any packet takes more than 8n time units
to reach its destination.
The structure of this argument is pretty typical for applications of Cher-
noff bounds: we get a very small bound on the probability that something
bad happens by applying Chernoff bounds to a part of the problem where
we have independence, then use the union bound to extend this to the full
problem where we dont.
CHAPTER 5. CONCENTRATION BOUNDS 74
1 x
and 1 = 2 1+ c . So
1 X c 1 X c
h i
X
E e E 1 e + 1+ e
2 c 2 c
ec + ec ec ec
= E [X] + E [X]
2 2c 2c
ec + ec
=
2
= cosh(c).
ex + ex
cosh x =
2
1 xn X
!
X (x)n
= +
2 n=0 n! n=0 n!
X x2n
=
n=0
(2n)!
X x2n
n=0
2n n!
X (x2 /2)n
=
n=0
n!
x2 /2
=e .
h i 2 /2
This gives E eX e(c) .
CHAPTER 5. CONCENTRATION BOUNDS 76
Lets see how good a bound this gets us for our usual test problem of
bounding Pr [S = n] where S = ni=1 Xi is the sum of n independent fair
P
gives
" n # !
X n2
Pr Yi n exp
i=1
2n
= en/2 = ( e)n .
Since e 1.649 . . . , this is actually slightly better than the (2/ e)n
bound we get using Chernoff bounds.
On the other hand, Chernoff bounds work better if we have a more
skewed distribution on the Xi ; for example, in the balls-in-bins case, each
Xi is a Bernoulli random variable with E [Xi ] = 1/n. Using Hoeffdings
inequality, we get a bound ci on |Xi E [Xi ]| of only 1 1/n, which puts
Pn 2
i=1 ci very close to n, requiring t = ( n) before we get any non-trivial
bound out of (5.3.1), pretty much the same as in the fair-coin case (which is
not surprising, since Hoeffdings inequality doesnt know anything about the
distribution of the Xi ). But weve already seen that Chernoff gives us that
P
Xi = O(log n/ log log n) with high probability in this case.
Note: There is an asymmetrical version of Hoeffdings inequality in which
ai Xi bi , but E [Xi ] is still zero for all Xi . In this version, the bound is
" n # !
X 2t2
Pr Xi t exp Pn 2
. (5.3.3)
i=1 i=1 (bi ai )
2. E [St+1 | Ft ] = St .
This means that even if we include any extra information we might have
at time t, we still cant predict St+1 any better than by guessing the current
value St . This alternative definition will be important in some special cases,
as when St is a function of some other collection of random variables that
we use to define the Ft . Because Ft includes at least as much information as
S0 , . . . , St , it will always be the case that any sequence {(St , Ft )} that is a
martingale in the general sense gives a sequence {St } that is a martingale in
the more specialized E [St+1 | S0 , . . . , St ] = St sense.
Martingales were invented to analyze fair gambling games, where your
return over some time interval is not independent of previous outcomes (for
example, you may change your bet or what game you are playing depending
on how things have been going for you), but it is always zero on average
given previous information.10 The nice thing about martingales is they allow
for a bit of dependence while still acting very much like sums of independent
random variables.
Where this comes up with Hoeffdings inequality is that we might have a
process that is reasonably well-behaved, but its increments are not technically
independent. For example, suppose that a gambler plays a game where
10
Real casinos give negative expected return, so your winnings in a real casino form
a supermartingale with St E [St+1 | S0 . . . St ]. On the other hand, the casinos take,
in a well-run casino, is a submartingale, a process with St E [St+1 | S0 . . . St ]. These
definitions also generalize in the obvious way to the {(St , Ft )} case.
CHAPTER 5. CONCENTRATION BOUNDS 79
in the proof of Theorem 5.3.1and the rest follows using the same argument.
The
hQonly trickyi part is weh cani no longer use independence to transform
n X into ni=1 E eXi .
Q
E i=1 e i
able that takes on the average value of eXi for each setting of X1 . . . Xi1 .
We can applyhthe same analysisias in the proof of 5.3.1 to show that this
X 2
means that E e i
X1 . . . Xi1 e(ci ) /2 always.
The trick is to use the fact that, for any random variables X and Y ,
E [XY ] = E [E [XY | X]] = E [X E [Y | X]]. hQ i 2
We argue by induction on n that E ni=1 eXi ni=1 e(c) /2 . The
Q
CHAPTER 5. CONCENTRATION BOUNDS 80
Some extensions:
The asymmetric version of Hoeffdings inequality (5.3.3) also holds for
martingales. So if each increment Xi satisfies ai Xi bi always,
" n # !
X 2t2
Pr Xi t exp Pn 2
. (5.3.5)
i=1 i=1 (bi ai )
11
The corresponding notion in the other direction is a submartingale. See 8.2.
12
This is known as a Doob decomposition and can be used to extract a martingale
{Zi } from any stochastic process {Xi }. For general processes, Yi = Xi Zi will still be
predictable, but may not satisfy Yi 0.
CHAPTER 5. CONCENTRATION BOUNDS 81
Suppose that we stop the process after the first time with S =
P
i=1 Xi t. This is equivalent to making a new variable Yi that is
zero whenever Si1 t and equal to Xi otherwise. This doesnt affect
the conditions E [Yi | Y1 . . . Yi1 ] = 0 or |Yi | ci , but it makes it so
Pn
Yi t if and only if maxkn ki=1 Xi t. Applying (5.3.4) to
P
P i=1
Yi then gives
k
" # !
X t2
Pr max Xi t exp Pn 2 . (5.3.7)
kn
i=1
2 i=1 ci
which implies
f (x1 , . . . , xt , x+
t+1 , xt+2 , . . . , xn ) f (x1 , . . . , xt , xt+1 , xt+2 , . . . , xn ) ct+1 ,
13
A sequence of random variables of the form Yt = E [Z | Ft ], where F0 F1 F2 . . .
is a called a Doob martingale. The proof that it is a martingale is immediate from
the general version of the law of iterated expectation E [Yt+1 ] Ft = E [E [Z] Ft+1 Ft ] =
E [Z] Ft = Yt .
CHAPTER 5. CONCENTRATION BOUNDS 83
the same thing without the absolute value. But then when we take expecta-
tions, we get
h i h i
E f (x1 , . . . , xt , x+
t+1 , Xt+2 , . . . , Xn E f (x1 , . . . , xt , xt+1 , Xt+2 , . . . , Xn +ct+1 ,
since we are just averaging the difference over all choices of xt+2 , . . . , xn .
This means that, for any fixed value of x1 through xt , the maximum and
minimum values of Yt+1 differ by at most ct+1 .
Since Yt must lie somewhere in between these values, we get that |Yt+1
Yt | so we can apply Azuma-Hoeffding to get Pr [Yn Y0 t]
ct+1 always,
2
exp 2 Ptn c2
. But this overestimates the possible range of Yt+1 ; we have
i=1 i
in fact shown that for any fixed x1 , . . . , xt , there exists bounds at+1
Yt+1 Yt bt+1 such that bt+1 at+1 = ct+1 . We would like to use this
to apply the asymmetric version of Azuma-Hoeffding given in (5.3.5). A
complication is that the specific values of at+1 and bt+1 depend on the
previous values x1 , . . . , xt , even though their difference bt+1 at+1 does not.
Fortunately, McDiarmid shows that the inequality works anyway, giving:
Since f satisfies the same constraints as f , the same bound holds for
Pr [f (X1 , . . . , Xn ) E [f (X1 , . . . , Xn )] t].
5.3.4 Applications
Here are some applications of the preceding inequalities. Most of these are
examples of the method of bounded differences.
tossed into, and let Y = f (X1 , . . . , Xm ) be the number of empty bins, then
changing a single Xi can change f by at most 1. So from (5.3.11) we have
2
Pr [Y n(1 1/n)m + t] e2t /m .
so far and the summation gives an upper bound on the expected number of
comparisons remaining.
To show that this is in fact a supermartingale, observe that if we partition
a block of size n we add n to Ct but replace the cost bound 2n ln n by an
expected
1 n1
Z n
X 4
2 2k ln k n ln n
n k=0 n 2
!
4 n2 ln n n2
= ln 2 + 1
n 2 4
= 2n ln n n ln 2 + 1
< 2n ln n n.
The net change is less than ln 2. The fact that its not zero suggests
that we could improve the 2n ln n bound slightly, but since its going down,
we have a supermartingale.
CHAPTER 5. CONCENTRATION BOUNDS 86
Lets try to get a bound on how much Xt changes at each step. The Ct
part goes up by at most n 1. The summation can only go down; if we split
a block of size ni , the biggest drop we get is if we split it evenly,15 This gives
a drop of
n1 n1 n1
2n ln n 2 2 ln = 2n ln n 2(n 1) ln n
2 2 2n
2n
= 2n ln n 2(n 1)(ln n ln )
n1
2n 2n
= 2n ln n 2n ln n + 2n ln + 2 ln n 2 ln
n1 n1
= 2n O(1) + O(log n)
= O(n).
where is the expected payoff of the best arm, and Ti counts the number
of times we pull arm i?
The tricky part here is that when we pull an arm and get a bad return,
we dont know if we were just unlucky this time or its actually a bad arm.
So we have an incentive to try lots of different arms. On the other hand, the
more we pull a genuinely inferior arm, the worse our overall return. Wed like
to adopt a strategy that trades off between exploration (trying new arms)
and exploitation (collecting on the best arm so far) to do as best we can in
comparison to a strategy that always pulls the best arm.
ni
Now consider xi = n1i j=1
P
X where each Xj lies between 0 and 1. This
Pnij
is equivalent to having xi = j=1 Yj where Yj = Xj /ni lies between 0 and
1/ni . So (5.3.14) says that
" s #
2 ln n 2 2
Pr E [xi ] xi e2( (2 ln n)/ni ) /(ni (1/ni ) )
ni
= e4 ln n
= n4 . (5.3.15)
[0, 1], then its expected regret after any number n of plays is at most
! K
X ln n 2 X
8 + 1+ j . (5.3.16)
i:i <
i 3 j=1
2ct,si i ,
giving
8 ln t
si .
2i
This explains (after multiplying by the regret i ) the first term in (5.3.16).
CHAPTER 5. CONCENTRATION BOUNDS 91
For the other sources of bad pulls, apply the union bound to the 2t4
error probabilities we previously computed for all choices of t n, s 1,
and si > `. This gives
n X
t1 t1
2t4 < 2 t2 t4
X X X
n
" #
1 X C
sup Pr Xi x (x) 3 , (5.4.1)
<x< n i=1 n
18
Sometimes written Berry-Essen theorem to help with the pronunciation of Esseens
last name.
CHAPTER 5. CONCENTRATION BOUNDS 92
where the xi are constants with |xi | 1 and the i are independent 1 fair
coin-flips, then Pr [| ni=1 i xi | r] is maximized by making all the xi equal
P
to 1. This shows that any distribution where the xi are all reasonably large
will not be any more concentrated than a binomial distribution.
There has been a lot of more recent work on variants of the Littlewood-
Offord problem, much of it by Terry Tao and Van Vu. See http://terrytao.
wordpress.com/2009/02/16/a-sharp-inverse-littlewood-offord-theorem/
for a summary of much of this work.
Chapter 6
These are data structures that are either trees or equivalent to trees, and use
randomization to maintain balance. Well start by reviewing deterministic
binary search trees and then add in the randomization.
93
CHAPTER 6. RANDOMIZED SEARCH TREES 94
y x
x C A y
A B B C
4 1
2 6 2
1 3 5 7 3
1 7
3 6
2 4
since the depth of each node is equal to 1 plus the number of comparisons it
participates in as a non-pivot, and (using the same argument as for Hoares
FIND in 3.6.3) that the height of the tree is O(log n) with high probability.1
When n is small, randomized binary search trees can look pretty scraggly.
Figure 6.3 shows a typical example.
1
The argument for Hoares FIND is that any node has at most 3/4 of the descendants
of its parent on average; this gives for any node x that Pr [depth(x) > d] (3/4)d1 n, or
a probability of at most nc that depth(x) > 1 + (c + 1) log(n)/ log(4/3) 1 + 6.952 ln n
for c = 1, which we need to apply the union bound. The right answer for the actual height
of a randomly-generated search tree in the limit is 4.31107 ln n [Dev88] so this bound
is actually pretty close. The real height is still nearly a factor of three worse than for a
completely balanced tree, which has max depth bounded by 1 + lg n 1 + 1.44269 ln n.
CHAPTER 6. RANDOMIZED SEARCH TREES 96
The problem with this approach in general is that we dont have any
guarantees that the input will be supplied in random order, and in the
worst case we end up with a linked list, giving O(n) worst-case cost for all
operations.
6.3 Treaps
The solution to bad inputs is the same as for QuickSort: instead of assuming
that the input is permuted randomly, we assign random priorities to each
element and organize the tree so that elements with higher priorities rise
to the top. The resulting structure is known as a treap [SA96], because it
satisfies the binary search tree property with respect to keys and the heap
property with respect to priorities.2
Theres an extensive page of information on treaps at http://faculty.
washington.edu/aragon/treaps.html, maintained by Cecilia Aragon, the
co-inventor of treaps; they are also discussed at length in [MR95, 8.2]. Well
give a brief description here.
To insert a new node in a treap, first walk down the tree according to
the key and insert the node as a new leaf. Then go back up fixing the heap
property by rotating the new element up until it reaches an ancestor with
the same or higher priority. (See Figure 6.4 for an example.) Deletion is
the reverse of insertion: rotate a node down to a leaf (by swapping with its
higher-priority child at each step), and then prune it off.
Because of the heap property, the root of each subtree is always the
element in that subtree with the highest priority. This means that the
structure of a treap is completely determined by the priorities and the keys,
no matter what order the elements arrive in. We can imagine in retrospect
that the treap is constructed recursively by choosing the highest-priority
element as the root, then organizing all smaller-index and all larger-index
nodes into the left and right subtrees by the same rule.
If we assign the priorities independently and uniformly at random from a
sufficiently large set ((n2 ) is enough in the limit), then we get no duplicates,
and by symmetry all n! orderings are equally likely. So the analysis of the
depth of a treap with random priorities is identical to the analysis of a binary
2
The name treap for this data structure is now standard but the history is a little
tricky. According to Seidel and Aragon, essentially the same data structure (though with
non-random priorities) was previously called a cartesian tree by Vuillemin [Vui80], and the
word treap was initially applied by McCreight to a different data structuredesigned
for storing two-dimensional datathat was called a priority search tree in its published
form. [McC85].
CHAPTER 6. RANDOMIZED SEARCH TREES 97
1,60 1,60
\ \
2,3 --> 3,26
\ /
(3,26) 2,3
5,78 5,78
/ \ / \
1,60 6,18 --> 1,60 7,41
\ \ \ /
3,26 (7,41) 3,26 6,18
/ \ / \
2,3 4,24 2,3 4,24
Figure 6.4: Inserting values into a treap. Each node is labeled with k, p where
k is the key and p the priority. Insertion of values not requiring rotations
are not shown.
CHAPTER 6. RANDOMIZED SEARCH TREES 98
search tree with random insertion order. Its not hard to see that the costs
of search insertion, and deletion operations are all linear in the depth of the
tree, so the expected cost of each of these operations is O(log n).
6.3.2 Analysis
The analysis of treaps as carried out by Seidel and Aragon [SA96] is a nice
example of how to decompose a messy process into simple variables, much
like the linearity-of-expectation argument for QuickSort (1.3.2). The key
observation is that its possible to bound both the expected depth of any node
and the number of rotations needed for an insert or delete operation directly
from information about the ancestor-descendant relationship between nodes.
Define two classes of indicator variables. For simplicity, we assume that
the elements have keys 1 through n, which we also use as indices.
The nice thing about these indicator variables is that its easy to compute
their expectations.
CHAPTER 6. RANDOMIZED SEARCH TREES 99
For Ai,j , i will be the ancestor of j if and only if i has a higher priority
than j and there is no k between i and j that has an even higher prior-
ity: in other words, if i has the highest priority of all keys in the interval
[min(i, j), max(i, j)]. To see this, imagine that we are constructing the treap
recursively, by starting with all elements in a single interval and partitioning
each interval by its highest-priority element. Consider the last interval in
this process that contains both i and j, and suppose i < j (the j > i case is
symmetric). If the highest-priority element is some k with i < k < j, then i
and j are separated into distinct intervals and neither is the ancestor of the
other. If the highest-priority element is j, then j becomes the ancestor of i.
The highest-priority element cant be less than i or greater than j, because
then we get a smaller interval that contains both i and j. So the only case
where i becomes an ancestor of j is when i has the highest priority.
1
It follows that E [Ai,j ] = |ij|+1 , where the denominator is just the
number of elements in the range [min(i, j), max(i, j)].
For Ci;`,m , i is the common ancestor of both ` and m if and only if it is has
the highest priority in both [min(i, `), max(i, `)] and [min(i, m), max(i, m)].
It turns out that no matter what order i, `, and m come in, these intervals
overlap so that i must have the highest priority in [min(i, `, m), max(i, `, m)].
1
This gives E [Ci;`,m ] = max(i,`,m)min(i,`,m)+1 .
6.3.2.1 Searches
1.3 So
P
From the Ai,j variables we can compute depth(j) = i Ai,j
n
!
X 1
E [depth(j)] = 1
i=1
|i j| + 1
j n
X 1 X 1 1
= +
i=1
ji+1 i=j+1
i j + 1
j nj+1
X 1 X 1
= + 1
k=1
k k=2
k
= Hj + Hnj+1 2.
4 2 6
/ \ / \ / \
*2 6* => 1 4 or 4 7
/ \ / \ / \ / \
1 *3 5* 7 *3 6* *2 5*
/ \ \
5* 7 *3
Figure 6.5: Rotating 4 right shortens the right spine of its left subtree by
removing 2; rotating left shortens the left spine of the right subtree by
removing 6.
node that we got for QuickSort. We can also sum over all j to get the exact
value of the expected total path length (but we wont). These quantities
bound the expected cost of searches.
evaluates to zero.
It follows that the expected length of the right spine of the left subtree is
exactly
" n n
# n n
X X X 1 X 1
E Ai,`1 Ci;`1,` =
i=1 i=1 i=1
|i (` 1)| + 1 i=1 max(i, `) min(i, ` 1) + 1
`1 n `1 n
X 1 X 1 X 1 X 1
= +
i=1
` i i=` i ` + 2 i=1 ` i + 1 i=` i (` 1) + 1
`1
X 1 n`+2
X 1 X `
1 n`+2
X 1
= +
j=1
j j=2
j j=2 j j=2
j
1
=1 .
`
By symmetry, the expected length of the left spine of the right subtree is
1
1 n`+1 . So the total expected number of rotations needed to delete the
`-th element is
1 1
2 2.
` n`+1
HEAD TAIL
33 LEVEL 2
13 33 48 LEVEL 1
13 21 33 48 75 99 LEVEL 0
Figure 6.6: A skip list. The blue search path for 99 is superimposed on an
original image from [AS07].
lower levels. When inserted into the level i list, an element flips a coin that
tells it with probability p to insert itself in the level i + 1 list as well. The
result is that the element is represented by a tower of nodes, one in each
of the bottom 1 + X many layers, where X is a geometrically-distributed
random variable. An example of a small skip list is shown in Figure 6.6.
Searches in a skip list are done by starting in the highest-level list and
searching forward for the last node whose key is smaller than the target; the
search then continues in the same way on the next level down. To bound the
expected running time of a search, it helps to look at this process backwards;
the reversed search path starts at level 0 and continues going backwards
until it reaches the first element that is also in a higher level; it then jumps
to the next level up and repeats the process. The nice thing about this
reversed process is that it has a simple recursive structure: if we restrict a
skip list to only those nodes to the left of and at the same level or higher
of a particular node, we again get a skip list. Furthermore, the structure of
this restricted skip list depends only on coin-flips taken at nodes within it,
so its independent of anything that happens elsewhere in the full skip list.
We can analyze this process by tracking the number of nodes in the
restricted skip list described above, which is just the number of nodes in
the current level that are earlier than the current node. If we move left,
this drops by 1; if up, this drops to p times its previous value on average.
So the number of such nodes Xk after k steps satisfies E [Xk+1 | Xk ] =
(1 p)(Xk 1) + p(p E [Xk ]) = (1 p + p2 )Xk (1 p)2 (1 p + p2 )Xk ,
and in general we get E [Xk ] (1 p + p2 )k X0 = (1 p + p2 )n. (We can
substitute the rank of the starting node for n if we want a slightly tighter
bound.) This is minimized at p = 1/2, giving E [Xk ] (3/4)k n, suspiciously
similar to the bound we computed before for random binary search trees.
When Xk = 0, our search is done, so if T is the time to search, we have
Pr [T k] = Pr [Xk 1] (3/4)k n, by Markovs inequality. In particular, if
CHAPTER 6. RANDOMIZED SEARCH TREES 103
p is approximately 1/p.
Like treaps, skip lists can be split an merged in a straightforward way.
The difference is that in a skip list, its enough to cut (or recreate) all the
pointers crossing the boundary, without changing the structure of the rest of
the list.
Chapter 7
Hashing
The basic idea of hashing is that we have keys from a large set U , and wed
like to pack them in a small set M by passing them through some function
h : U M , without getting too many collisions, pairs of distinct keys x
and y with h(x) = h(y). Where randomization comes in is that we want this
to be true even if the adversary picks the keys to hash. At one extreme, we
could use a random function, but this will take a lot of space to store.1 So
our goal will be to find functions with succinct descriptions that are still
random enough to do what we want.
The presentation in this chapter is based largely on [MR95, 8.4-8.5]
(which is in turn based on work of Carter and Wegman [CW77] on universal
hashing and Fredman, Komls, and Szemerdi [FKS84] on O(1) worst-case
hashing); on [PR04] and [Pag06] for cuckoo hashing; and [MU05, 5.5.3] for
Bloom filters.
104
CHAPTER 7. HASHING 105
Lemma
For any family H, there exist x, y such that (x, y, H)
7.2.1.
|H| m1
m 1 |U |1 .
Proof. Well count collisions in the inverse image of each element z. Since
all distinct pairs of elements of h1 (z) collide with each other, we have
(h1 (z), h1 (z), h) = h1 (z) h1 (z) 1 .
CHAPTER 7. HASHING 107
|H|
(U, U, H) |U |(|U | m).
m
There are exactly |U |(|U | 1) ordered pairs x, y for which (x, y, H) might
not be zero; so the Pigeonhole principle says some pair x, y has
|H| |U |(|U | m)
(x, y, H)
m |U |(|U | 1)
|H| m1
= 1 .
m |U | 1
m1
Since 1 |U |1 is likely to be very close to 1, we are happy if we get the
2-universal upper bound of |H|/m.
Why we care about this: With a 2-universal hash family, chaining using
linked lists costs O(1 + s/n) expected time per operation. The reason is that
the expected cost of an operation on some key x is proportional to the size
of the linked list at h(x) (plus O(1) for the cost of hashing itself). But the
expected size of this linked list is just the expected number of keys y in the
dictionary that collide with x, which is exactly s(x, y, H) s/n.
CHAPTER 7. HASHING 108
Lemma 7.2.2. Let hab (x) = (ax + b mod p) mod m, where a Zp \ {0} , b
Zp , and p is a prime m. Then {hab } is 2-universal.
Proof. Again, we count collisions. Split hab (x) as g(fab (x)) where fab (x) =
ax + b mod p and g(x) = x mod m.
The intuition is that after feeding any distinct x and y through fab , all
distinct pairs of values r and s are equally likely. We then show that feeding
these values to g produces no more collisions than expected.
The formal statement of the intuition is that for any 0 x, y p 1
with x 6= y, (x, y, H) = (Zp , Zp , g).
To prove this, fix x and y, and consider some pair r 6= s Zp . Then the
equations ax + b = t and ay + b = u have a unique solution for a and b mod
p (because Zp is a finite field). So (fab (x), fab (y)) is a bijection between pairs
P P
a, b and pairs u, u and thus (x, y, H) = a,b (x, y, fab ) = t6=u (t, u, g) =
(Zp , Zp , g).
Now we just need to count how many distinct t and u collide. There are p
choices for t. For each t, there are at most dp/me values that map to the same
remainder mod m, but one of those values is equal to t, so this leaves only
dp/me 1 choices for u. But dp/me 1 (p + (m 1))/m 1 = (p 1)/m.
So (Zp , Zp , g) p(p 1)/m.
1
Since each choice of t and u occurs with probability p(p1) , this gives a
probability of a collision of at most 1/m.
costs from this can often be justified in practice by the reduction in costs
from working with powers of 2.
If we are willing to use more randomness (and more space), a method
called tabulation hashing (7.2.2) gives a simpler alternative that is 3-
universal.
3
Letting m be a power of 2 and using exclusive OR is convenient on real computers. If
for some reason we dont like this approach, the same technique, with essentially the same
analysis, works for arbitrary m if we replace bitwise XOR with addition mod m.
CHAPTER 7. HASHING 110
Now we want to show that when n = 3, this actually works for all possible
distinct strings x, y, and z. Let S be the set of indices i such that yi 6= xi ,
and similarly let T be the set of indices i such that zi 6= xi ; note that both
sets must be non-empty, since y 6= x and z 6= x. If S \ T is nonempty, then
(a) there is some index i in T where zi =6 xi , and (b) there is some index j in
S \ T where yi 6= xi = zi ; in this case, ordering the strings as x, z, y gives
the independence property above. If T \ S is nonempty, order them as x, z,
y instead. Alternatively, if S = T , then yi = 6 zi for some i in S (otherwise
y = z, since they both equal x on all positions outside S). In this case, xi ,
yi , and zi are all distinct.
For n = 4, we can have strings aa, ab, ba, and bb. If we take the
bitwise exclusive OR of all four hash values, we get zero, because each
character is included exactly twice in each position. So the hash values are
not independent, and we do not get 4-independence in general.
However, even though tabulation hashing is not 4-independent, most
reasonably small sets of inputs do give independence. This can be used to
show various miraculous properties like working well for cuckoo hashing.
n
Lemma 7.3.1. If H is 2-universal and |S| = n with 2 m, then there is
a perfect h H for S.
Proof. Let h be chosen uniformly at random from H. For each unordered pair
x 6= y in S, let Xxy be the indicator variable for the even that h(x) = h(y),
P
and let C = x6=y Xxy be the total number of collisions in S. Each Xxy
has expectation at most 1/m, so E [C] n2 /m < 1. But we we can write
E [C] as E [C | C = 0] Pr [C = 0] + E [C | C 1] Pr [C 6= 0] Pr [C 6= 0]. So
Pr [C 6= 0] n2 /m < 1, giving Pr [C = 0] > 0. But if C is zero with nonzero
The time to do a search is O(1) in the worst case: O(1) for the outer hash
plus O(1) for the inner hash.
The last equality holds because each ordered pair of distinct values in S that
map to the same bucket i corresponds to exactly one collision in (S, S, h).
Since H is 2-universal, we have (S, S, H) |H|s(s 1)/n. But then
the Pigeonhole principle says there exists some h H with (S, S, h)
CHAPTER 7. HASHING 112
1 Pn 2
n(n 1)/n = n 1. This gives
|H| (S, S, H) i=1 ni n + (n 1) =
2n 1 = O(n).
If we want to find a good h quickly, increasing the size of the outer table
to n/ gives us a probability of at least 1 of getting a good one, using
essentially the same argument as for perfect hash functions.
7.4.1 Structure
We have a table T of size n, with two separate, independent hash functions h1
and h2 . These functions are assumed to be k-universal for some sufficiently
large value k; as long as we never look at more than k values at once, this
means we can treat them effectively as random functions. In practice, using
crummy hash functions seems to work just fine, a common property of hash
tables. There are also specific hash functions that have been shown to work
with particular variants of cuckoo hashing [PR04, PT12]. We will avoid these
issues by assuming that our hash functions are actually random.
Every key x is stored either in T [h1 (x)] or T [h2 (x)]. So the search
procedure just looks at both of these locations and returns whichever one
contains x (or fails if neither contains x).
To insert a value x1 = x, we must put it in T [h1 (x1 )] or T [h2 (x1 )]. If one
or both of these locations is empty, we put it there. Otherwise we have to
kick out some value that is in the way (this is the cuckoo part of cuckoo
hashing, named after the bird that leaves its eggs in other birds nests). We
CHAPTER 7. HASHING 113
do this by letting x2 = T [h1 (x1 )] and writing x1 to T [h1 (x1 )]. We now have
a new nestless value x2 , which we swap with whatever is in T [h2 (x2 )]. If
that location was empty, we are done; otherwise, we get a new value x3 that
we have to put in T [h1 (x3 )] and so on. The procedure terminates when we
find an empty spot or if enough iterations have passed that we dont expect
to find an empty spot, in which case we rehash the entire table. This process
can be implemented succinctly as shown in Algorithm 7.1.
1 procedure insert(x)
2 if T (h1 (x) = x or T (h2 (x)) = x then
3 return
4 pos h1 (x)
5 for i 1 . . . n do
6 if T [pos] = then
7 T [pos] x
8 return
9 x T [pos]
10 if pos = h1 (x) then
11 pos h2 (x)
12 else
13 pos h1 (x)
A detail not included in the above code is that we always rehash (in
theory) after m2 insertions; this avoids potential problems with the hash
functions used in the paper not being universal enough. We will avoid this
issue by assuming that our hash functions are actually random (instead of
being approximately n-universal with reasonably high probability). For a
more principled analysis of where the hash functions come from, see [PR04].
An alternative hash family that is known to work for a slightly different
variant of cuckoo hashing is tabulation hashing, as described in 7.2.2; the
proof that this works is found in [PT12].
CHAPTER 7. HASHING 114
7.4.2 Analysis
The main question is how long it takes the insertion procedure to terminate,
assuming the table is not too full.
First lets look at what happens during an insert if we have a lot of
nestless values. We have a sequence of values x1 , x2 , . . . , where each pair of
values xi , xi+1 collides in h1 or h2 . Assuming we dont reach the loop limit,
there are three main possibilities (the leaves of the tree of cases below):
1. Eventually we reach an empty position without seeing the same key
twice.
2. Eventually we see the same key twice; there is some i and j > i such
that xj = xi . Since xi was already moved once, when we reach it
the second time we will try to move it back, displacing xi1 . This
process continues until we have restored x2 to T [h1 (x1 )], displacing x1
to T [h2 (x1 )] and possibly creating a new sequence of nestless values.
Two outcomes are now possible:
(a) Some x` is moved to an empty location. We win!
(b) Some x` is moved to a location weve already looked at. We lose!
We find we are playing musical chairs with more players than
chairs, and have to rehash.
Lets look at the probability that we get the last, closed loop case. Follow-
ing Pagh-Rodler, we let v be the number of distinct nestless keys in the loop.
Since v includes x1 , v is at least 1. We can now count how many different
ways such a loop can form.
There are at most v 3 choices for i, j, and `, mv1 choices of cells for the
loop, and nv1 choices for the non-x1 elements of the loop. For each non-xi
element, its initial placement may determined by either h1 or h2 ; this gives
another 2v1 choices.4 This gives a total of v 3 (2nm)v1 possible closed loops
starting with x1 that have v distinct nodes.
Since each particular loop allows us to determine both h1 and h2 for all v
of its elements, the probability that we get exactly these hash values (so that
the loop occurs) is m2v . Summing over all closed loops with v elements
gives a total probability of
v 3 (2nm)v1 m2v = v 3 (2n)v1 mv1
= v 3 (2n/m)v1 m2 .
4
The original analysis in [PR04] avoids this by alternating between two tables, so that
we can determine which of h1 or h2 is used at each step by parity.
CHAPTER 7. HASHING 115
The series converges if 2n/m < 1, so for any fixed < 1/2, the probability
of any closed loop forming is O(m2 ).
If we do hit a closed loop, then we pay O(m) time to scan the existing
table and create a new empty table, and O(n) = O(m) time on average to
reinsert all the elements into the new table, assuming that this reinsertion
process doesnt generate any more closed loops and that the average cost of an
insertion that doesnt produce a closed loop is O(1), which we will show below.
But the rehashing step only fails with probability O(nm2 ) = O(m1 ), so if
it does fail we can just try again until it works, and the expected total cost
is still O(m). Since we pay this O(m) for each insertion with probability
O(m2 ), this adds only O(m1 ) to the expected cost of a single insertion.
Now we look at what happens if we dont get a closed loop. This doesnt
force us to rehash, but if the path is long enough, we may still pay a lot to
do an insertion.
Its a little messy to analyze the behavior of keys that appear more than
once in the sequence, so the trick used in the paper is to observe that for any
sequence of nestless keys x1 . . . xp , there is a subsequence of size p/3 with no
repetitions that starts with x1 . This will be either the sequence S1 given by
x1 . . . xj1 the sequence starting with the first place we try to insert x1 or
S2 given by x1 = xi+j1 . . . xp , the sequence starting with the second place
we try to insert x1 . Between these we have a third sequence S3 where we
undo some of the moves made in S1 . Because |S1 | + |S3 | + |S2 | p, at least
one of thee subsequences has size p/3. But |S3 | |S1 |, so it must be either
S1 or S2 .
We can then argue that the probability that we get a sequence of v
distinct keys in either S1 or S2 most 2(n/m)v1 . The (n/m)v1 is because
we need to hit a nonempty spot (which happens with probability at most
n/m) for the first v 1 elements in the path, and since we assume that our
hash functions are random, the choices of these v 1 spots are all independent.
The 2 is from the union bound over S1 and S2 . If T is the insertion time,
we get E [T ] =
P v1 = O(1), assuming n/m
v=1 Pr [T v]
P
v=1 2(n/m)
is bounded by a constant less than 1. Since we already need n/m 1/2 to
avoid the bad closed-loop case, we can use this here as well.
An annoyance with cuckoo hashing is that it has high space overhead
compared to more traditional hash tables: in order for the first part of the
CHAPTER 7. HASHING 116
analysis above to work, the table must be at least half empty. This can be
avoided at the cost of increasing the time complexity by choosing between
d locations instead of 2. This technique, due to Fotakis et al. [FPSS03], is
known as d-ary cuckoo hashing; for suitable choice of d it uses (1 + )n
space and guarantees that a lookup takes O(1/) probes while insertion
takes (1/)O(log log(1/)) steps in theory and appears to take O(1/) steps in
experiments done by the authors.
7.6.1 Construction
Bloom filters are a highly space-efficient randomized data structure invented
by Burton H. Bloom [Blo70] that store sets of data, with a small probability
that elements not in the set will be erroneously reported as being in the set.
Suppose we have k independent hash functions h1 , h2 , . . . , hk . Our mem-
ory store A is a vector of m bits, all initially zero. To store a key x, set
A[hi (x)] = 1 for all i. To test membership for x, see if A[hi (x)] = 1 for all
CHAPTER 7. HASHING 117
i. The membership test always gives the right answer if x is in fact in the
Bloom filter. If not, we might decide that x is in the Bloom filter anyway.
Pr [A[i] = 1] 1 (1 1/m)kn
1 ek(n/m)(1+1/m)
= 1 ek(1+1/m)
0
= 1 ek
where = n/m is the load factor and 0 = (1 + 1/m) is the load factor
fudged upward by a factor of 1 + 1/m to make the inequality work.
Suppose now that we check to see if some value x that we never inserted
in the Bloom filter appears to be present anyway. This occurs if A[hi (x)] = 1
for all i. Since each hi (x) is assumed to be an independent uniform probe of
A, the probability that they all come up 1 conditioned on A is
P k
A[i]
. (7.6.1)
m
0
We have an upper bound E [ A[i]] m 1 ek , and if we were born
P
inequality also goes in the wrong direction, because f is convex for k > 1.
P
So instead we will prove a concentration bound on S = A[i].
Because the A[i] are not independent, we cant use off-the-shelf Chernoff
bounds. Instead, we rely on McDiarmids inequality. Our assumption is
that the locations of the kn ones that get written to A are independent.
Furthermore, changing the location of one of these writes changes S by at most
2
1. So McDiarmids inequality (5.3.11)
q gives Pr [S E [S] + t] e2t /kn ,
which is bounded by nc for t 12 ckn log n. So as long as a reasonably
large fraction of the array is likely to be full, the relative error from assuming
S = E [S] is likely to be small. Alternatively, if the array is mostly empty,
then we dont care about the relative error so much because the probability
of getting a false positive will already be exponentially small as a function of
k.
So lets assume for simplicity that our false positive probability is exactly
0
(1 ek )k . We can choose k to minimize this quantity for fixed 0 by
doing the usual trick of taking a derivative and setting it to zero; to avoid
weirdness with the k in the exponent, it helps to take the logarithm first
(which doesnt affect the location of the minimum), and it further helps to
0
take the derivative with respect to x = e k instead of k itself. Note that
when we do this, k = 10 ln x still depends on x, and we will deal with this
by applying this substitution at an appropriate point.
Compute
d d
ln (1 x)k = k ln(1 x)
dx dx
d 1
= 0 ln x ln(1 x)
dx
1 ln(1 x) ln x
= 0 .
x 1x
7.6.4 Applications
Historically, Bloom filters were invented to act as a way of filtering queries
to a database table through fast but expensive7 RAM before looking up the
actual values on a slow but cheap tape drive. Nowadays the cost of RAM is
low enough that this is less of an issue in most cases, but Bloom filters are
still popular in networking and in distributed databases.
In networking, Bloom filters are useful in building network switches, where
incoming packets need to be matched against routing tables in fractions of a
nanosecond. Bloom filters work particularly well for this when implemented
in hardware, since the k hash functions can be computed in parallel. False
positives, if infrequent enough, can be handled by some slower backup
mechanism.
In distributed databases, Bloom filters are used in the Bloomjoin algo-
rithm [ML86]. Here we want to do a join on two tables stored on different
machines (a join is an operation where we find all pairs of rows, one in each
table, that match on some common key). A straightforward but expensive
way to do this is to send the list of keys from the smaller table across the
network, then match them against the corresponding keys from the larger
table. If there are ns rows in the smaller table, nb rows in the larger table,
and j matching rows in the larger table, this requires sending ns keys plus j
7
As much as $0.10/bit in 1970.
CHAPTER 7. HASHING 121
rows. If instead we send a Bloom filter representing the set of keys in the
smaller table, we only need to send lg(1/)/ ln 2 bits for the Bloom filter plus
an extra nb rows on average for the false positives. This can be cheaper
than sending full keys across if the number of false positives is reasonably
small.
complex tasks like finding heavy hittersindices with high weight. The
easiest case is approximating ai when all the ct are non-negative, so well
start with that.
The update rule: Given an update (it , ct ), increment c[j, hj (it )] by ct for
j = 1 . . . d. (This is the count part of count-min.)
7.6.6.2 Queries
Lets start with point queries. Here we want to estimate ai for some
fixed i. There are two cases; the first handles non-negative increments only,
while the second handles arbitrary increments. In both cases we will get an
estimate whose error is linear in both the error parameter and the `1 -norm
kak1 = i |ai | of a. It follows that the relative error will be low for heavy
P
points, but we may get a large relative error for light points (and especially
large for points that dont appear in the data set at all).
For the non-negative case, to estimate ai , compute a i = minj c[j, hj (i)].
(This is the min part of coin-min.) Then:
i ai ,
a (7.6.2)
and
ai ai + kak1 ] 1 .
Pr [ (7.6.3)
Proof. The lower bound is easy. Since for each pair (i, ct ) we increment each
c[j, hj (i)] by ct , we have an invariant that ai c[j, hj (i)] for all j throughout
the computation, which gives ai a i = minj c[j, hj (i)].
For the upper bound, let Iijk be the indicator for the event that (i 6=
k) (hj (i) = hj (k)), i.e., that we get a collision between i and k using hj .
The 2-universality property of the hj gives E [Iijk ] 1/w /e.
Now let Xij = nk=1 Iijk ak . Then c[j, hj (i)] = ai + Xij . (The fact that
P
Xij 0 gives an alternate proof of the lower bound.) Now use linearity of
expectation to get
" n #
X
E [Xij ] = E Iijk ak
k=1
n
X
= ak E [Iijk ]
k=1
Xn
ak (/e)
k=1
= (/e)kak1 .
CHAPTER 7. HASHING 124
So Pr [c[j, hj (i)] > ai + kak1 ] = Pr [Xij > e E [Xij ]] < 1/e, by Markovs in-
equality. With d choices for j, and each hj chosen independently, the proba-
bility that every count is too big is at most (1/e)d = ed exp( ln(1/)) =
.
Now lets consider the general case, where the increments ct might be
negative. We still initialize and update the data structure as described in
7.6.6.1, but now when computing a i , we use the median count instead of
the minimum count: a i = median {c[j, hj (i)] | j = 1 . . . n}. Now we get:
Proof. The basic idea is that for the median to be off by t, at least d/2
rows must give values that are off by t. Well show that for t = 3kak1 , the
expected number of rows that are off by t is at most d/8. Since the hash
functions for the rows are chosen independently, we can use Chernoff bounds
to show that with a mean of d/8, the chances of getting all the way to d/2
are small.
In detail, we again define the error term Xij as above, and observe that
" #
X
E [|Xij |] = E Iijk ak
k
n
X
|ak E [Iijk ]|
k=1
Xn
|ak |(/e)
k=1
= (/e)kak1 .
Using Markovs inequality, we get Pr [|Xij |] > 3kak1 ] = Pr [|Xij | > 3e E [Xij ]] <
1/3e < 1/8. In order for the median to be off by more than 3kak1 , we need
d/2 of these low-probability events to occur. The expected number that
occur is = d/8, so applying the standard Chernoff bound (5.2.1) with = 3
CHAPTER 7. HASHING 125
we are looking at
Pr [S d/2] = Pr [S (1 + 3)]
(e3 /44 )d/8
(e3/8 /2)ln(1/)
= ln 23/8
< 1/4
(the actual exponent is about 0.31, but 1/4 is easier to deal with). This
immediately gives (7.6.4).
One way to think about this is that getting an estimate within kak1 of
the right value with probability at least 1 requires 3 times the width and
4 times the depthor 12 times the space and 4 times the timewhen we
arent assuming increments are non-negative.
Next, we consider inner products. Here we want to estimate a b, where
a and b are both stored as count-min sketches using the same hash functions.
The paper concentrates on the case where a and b are both non-negative,
which has applications in estimating the size of a join in a database. The
method is to estimate a b as minj w k=1 ca [j, k] cb [j, k].
P
For a single j, the sum consists of both good values and bad collisions; we
have w
Pn
k=1 ca [j, k] cb [j, k] =
P P
k=1 ai bi + p6=q,hj (p)=hj (q) ap bq . The second
term has expectation
X X
Pr [hj (p) = hj (q)] ap bq (/e)ap bq
p6=q p6=q
X
(/e)ap bq
p,q
(/e)kak1 kbk1 .
heavy hitters. But the tricky part is figuring out which elements they are.
Instead of trying to find the elements after the fact, we extend the data
structure and update procedure to track all the heavy elements found so
far (stored in a heap), as well as kak1 = ct . When a new increment (i, c)
P
comes in, we first update the count-min structure and then do a point query
i kak1 , we insert i into the heap, and if not, we delete i along
on ai ; if a
with any other value whose stored point-query estimate has dropped below
threshold.
The trick here is that the threshold kak1 only increases over time
(remember that we are assuming non-negative increments). So if some
element i is below threshold at time t, it can only go above threshold if it
shows up again, and we have a probability of at least 1 of including it then.
This means that every heavy hitter appears in the heap with probability at
least 1 .
The total space cost for this data structure is the cost of the count-min
structure plus the cost of the heap; this last part will be O((1 + )/) with
reasonably high probability, since this is the maximum number of elements
that have weight at least kak1 /(1 + ), the minimum needed to get an
apparent weight of kak1 even after taking into account the error in the
count-min structure.
which an -PLEB data structure with radius ` and centers P returns a point
p with d(q, p) (1 + )`; then return this point as the approximate nearest
neighbor.
This requires O(log1+ R) instances of the -PLEB data structure and
O(log log1+ R) queries. The blowup as a function of R can be avoided using
a more sophisticated data structure called a ring-cover tree, defined in the
paper. We wont talk about ring-cover trees because they are (a) complicated
and (b) not randomized. Instead, well move directly to the question of how
we solve -PLEB.
These are useful if p1 > p2 and r1 < r2 ; that is, we are more likely to hash
inputs together if they are closer. Ideally, we can choose r1 and r2 to build
-PLEB data structures for a range of radii sufficient to do binary search as
CHAPTER 7. HASHING 128
described above (or build a ring-cover tree if we are doing it right). For the
moment, we will aim for an (r1 , r2 )-PLEB data structure, which returns a
point within r1 with high probability if one exists, and never returns a point
farther away than r2 .
There is some similarity between locality-sensitive hashing and a more gen-
eral dimension-reduction technique known as the Johnson-Lindenstrauss
lemma [JL84]; this says that projecting n points in a high-dimensional space
to O(2 log n) dimensions using an appropriate random matrix preserves
`2 distances between the points to within relative error (in fact, even a
random matrix with 1 entries is enough [Ach03]). Unfortunately, dimension
reduction by itself is not enough to solve approximate nearest neighbors
in sublinear time, because we may still need to search a number of boxes
exponential in O(2 log n), which will be polynomial in n.
=n
= 1/`.
tance
computations. The cost to insert a point is just O(k` log(1/)) =
O n log1/p2 n log(1/) hash function evaluations, the same number as for
a query.
for any fixed r, which will correspond to an (r, r(1 + ))-PLEB. The main
thing we need to do, following [IM98] as always, is compute a reasonable
p1 ln(1r/d)
bound on = log log p2 = ln(1(1+)r/d) . This is essentially just a matter of
hitting it with enough inequalities, although there are a couple of tricks in
the middle.
Compute
ln(1 r/d)
=
ln(1 (1 + )r/d)
(d/r) ln(1 r/d)
=
(d/r) ln(1 (1 + )r/d)
ln((1 r/d)d/r )
=
ln((1 (1 + )r/d)d/r )
ln(e1 (1 r/d))
ln e(1+)
1 + ln(1 r/d)
=
(1 + )
1 ln(1 r/d)
= . (7.7.1)
1+ 1+
Note that we used the fact that 1 + x ex for all x in the denominator
and (1 x)1/x e1 (1 x) for x [0, 1] in the numerator. The first fact is
our usual favorite inequality.
The second can be proved in a number of ways. The most visually
intuitive is that (1 x)1/x and e1 (1 x) are equal at x = 1 and equal
in the limit as x goes to 0, while (1 x)1/x is concave in between 0 and
1 and e1 (1 x) is linear. Unfortunately it is rather painful to show that
(1 x)1/x is in fact concave. An alternative is to rewrite the inequality
(1 x)1x e1 (1 x) as (1 x)1/x1 e1 , apply a change of variables
y = 1/x to get (1 1/y)y1 e1 for y [1, ), and then argue that (a)
equality holds in the limit as y goes to infinity, and (b) the left-hand-side is
CHAPTER 7. HASHING 131
We now return to (7.7.1). Wed really like the second term to be small
enough that we can just write n as n1/(1+) . (Note that even though it looks
negative, it isnt, because ln(1 r/d) is negative.) So we pull a rabbit out of
a hat by assuming that r/d < 1/ ln n.8 This assumption can be justified by
modifying the algorithm so that d is padded out with up to d ln n unused
junk bits if necessary. Using this assumption, we get
Plugging into the formula for (r1 , r2 )-PLEB gives O(n1/(1+) log n log(1/))
hash function evaluations per query, each of which costs O(1) time, plus
O(n1/(1+) log(1/)) distance computations, which will take O(d) time each.
If we add in the cost of the binary search, we have to multiply this by
O(log log1+ R log log log1+ R), where the log-log-log comes from having to
adjust so that the error doesnt accumulate too much over all O(log log R)
steps. The end result is that we can do approximate nearest-neighbor queries
in
O n1/(1+) log(1/)(log n + d) log log1+ R log log log1+ R
time. For reasonably large, this is much better than naively testing against
all points in our database, which takes O(nd) time (although it does produce
an exact result).
8
Indyk and Motwani pull this rabbit out of a hat a few steps earlier, but its pretty
much the same rabbit either way.
CHAPTER 7. HASHING 132
8.1 Definitions
The general form of a martingale {Xt , Ft } consists of:
E [Xt+1 | Ft ] = Xt (8.1.1)
133
CHAPTER 8. MARTINGALES AND STOPPING TIMES 134
Xt E [Xt+1 | Ft ] (8.2.1)
Xt E [Xt+1 | Ft ] . (8.2.2)
In each case, what is sub or super is the value at the current time
compared to the expected value at the next time. Intuitively, a submartingale
corresponds to a process where you win on average, while a supermartingale
is a process where you lose on average. Casino games (in profitable casinos)
are submartingales for the house and supermartingales for the player.
Sub- and supermartingales can be reduced to martingales by subtracting
off the expected change at each step. For example, if {Xt } is a submartingale
with respect to {Ft }, then the process {Yt } defined recursively by
Y0 = X0
Yt+1 = Yt + Xt+1 E [Xt+1 | Ft ]
1
Different authors impose different conditions on the range of ; for example, Mitzen-
macher and Upfal [MU05] exclude the case = . We allow = to represent the
outcome where we never stop. This can be handy for modeling processes where this
outcome is possible, although in practice we will typically insist that it occurs only with
probability zero.
CHAPTER 8. MARTINGALES AND STOPPING TIMES 135
is a martingale, since
(a) Pr [ < ] = 1,
(b) E [|X |] < , and
h i
(c) limt E Xt 1[ >t] = 0.
Lemma 8.4.1. Let (Xht , Ft ) be aimartingale and a stopping time for {Ft }.
Then for any n N, E Xmin(,n) = E[X0 ].
Pt
Proof. Define Yt = X0 + i=1 (Xt Xt1 )1[ >t1]
h
. Then (Yt , Ft ) is a martin-
i
gale, because we can calculate E [Yt+1 | Ft ] = E Yt + (Xt+1 Xt )1[ >t] Ft =
3. Conclude that E [X0 ] = E [X ], since they are both limits of the same
sequence.
For the middle step, start with
X = Xmin(,n) + 1[ >n] (X Xn ).
This holds because either n, and we just get X , or > n, and we get
Xn + (X Xn ) = X .
Taking the expectation of both sides gives
h i h i
E [X ] = E Xmin(,n) + E 1[ >n] (X Xn ) .
h i
= E [X0 ] + E 1[ >n] (X Xn ) .
So if we can show that the right-hand term goes to zero in the limit, we are
done. h i
For the bounded-range case, we have |X Xn | 2M , so E 1[ >n] (X Xn )
which implies
h i h i h i
lim E [X ] = lim E Xmin(,n) + lim E 1[ >n] X lim E 1[ >n] Xn ,
n n n n
assuming all these limits exist and are finite. Weve already established that
the first limit is E [X0 ], which is exactly what we want. So we just need to
show that the other two limits both converge tohzero. Forithe last limit, we
just use condition (4c), which gives limn E 1[ >n] Xn = 0; no further
argument is needed. But we still need to show that the middle limit also
vanishes. h i P h i
Here we use condition (4b). Observe that E 1[ >n] X = t=n+1 E 1 X
[ =t] t .
h i
Compare this with E [X ] =
P
t=0 E 1[ =t] Xt ; this is an absolutely conver-
gent series (this is why we need condition (4b)), so in the limit the sum of
the terms for i = 0 . . . n converges to E [X ]. But this means that the sum
of the remaining terms for i = n + 1 . . . converges to zero. So the middle
term goes to zero as n goes to infinity. This completes the proof.
8.5 Applications
Here we give some example of the Optional Stopping Theorem in action. In
each case, the trick is to find an appropriate martingale and stopping time,
and let the theorem do all the work.
= Yt1 .
Pt
For the 1 random walk case, we have Vt = 1 always, giving V = t and E X2 =
i=1 i
2
E X0 + E [ ] when is a stopping time satisfying the conditions of the Optional Stopping
P
Theorem. For the general case, the same argument gives E X2 = E X02 + E V
t=1 t
instead: the expected square position of Xt is incremented by the conditional variance at
each step.
4
This would be a random walk with one absorbing barrier.
CHAPTER 8. MARTINGALES AND STOPPING TIMES 140
0 = E [YN ]
"N #
X
=E (Xi )
i=1
"N # "N #
X X
=E Xi E
i=1 i=1
"N #
X
=E Xi E [N ] .
i=1
This is the same formula as in 3.4.3.1, but weve eliminated the bound
on N and allowed for much more dependence between N and the Xi .8
who are still in play. For each i with x1 . . . xi = xki+1 . . . xk , there will be a
gambler with net winnings ij=1 2j1 = 2i 1. The remaining gamblers will
P
all be at 1.
Let i = 1 if x1 . . . xi = xki+1 . . . xk , and 0 otherwise. Then the number
of losers is given by ki=1 i and the total expected payoff is
P
k k
" #
X X
i
E [X ] = E ( i ) + i 2 1
i=1 i=1
k
" #
X
i
= E + i 2
i=1
= 0.
Markov chains
143
CHAPTER 9. MARKOV CHAINS 144
If you want to learn more about Markov chains than presented here or
in the textbook, they are usually covered in general probability textbooks
(for example, in [Fel68] or [GS01]), mentioned in many linear algebra text-
books [Str03], covered in some detail in stochastic processes textbooks [KT75],
and covered in exquisite detail in many books dedicated specifically to the
subject [KS76, KSK76]. Good sources for mixing times for Markov chains
are the textbook of Levin, Peres, and Wilmer [LPW09] and the survey pa-
per by Montenegro and Tetali [MT05]. An early reference on the mixing
times for random walks on graphs that helped inspire much subsequent
work is the Aldous-Fill manuscript [AF01], which can be found on-line at
http://www.stat.berkeley.edu/~aldous/RWG/book.html.
chain, we can control what this stationary distribution looks like, run
the chain for a while, and get a sample close to the stationary distribu-
tion.
In both cases we want to have a bound on how long it takes the Markov
chain to converge, either because it tells us when our algorithm terminates,
or because it tells us how long to mix it up before looking at the current
state.
9.1.1 Examples
A fair 1 random walk. The state space is Z, the transition probabilities
are pij = 1/2 if |i j| = 1, 0 otherwise. This is an example of a Markov
chain that is also a martingale.
A fair 1 random walk on a cycle. As above, but now the state space
is Z/m, the integers mod m. An example of a finite Markov chain.
one of its two variables uniformly at random, and invert it. Then
there is an absorbing state at any satisfying assignment. With a bit
of work, it can be shown that the Hamming distance between the
current assignment and some satisfying assignment follows a random
walk biased toward 0, giving a satisfying assignment after O(n2 ) steps
on average.
P = P
and
1 = 1
3
Given a square matrix A, a vector x is a right eigenvector of A with eigenvalue is
Ax = x. Similarly, a vector y is a left eigenvalue of A with eigenvalue if yA = A.
4
Spelling is important here. A stationery distribution would mean handing out office
supplies.
CHAPTER 9. MARKOV CHAINS 149
This is called the detailed balance equationsit says that in the station-
ary distribution, the probability of seeing a transition from i to j is equal to
the probability of seeing a transition from j to i). If this is the case, then
P P
i i pij = i j pji = j , which means that is stationary.
This often gives a very quick way to compute the stationary distribution,
since if we know i , and pij 6= 0, then j = i pij /pji . If the transition
probabilities are reasonably well-behaved (for example, if pij = pij for all
i, j), we may even be able to characterize the stationary distribution up to
a constant multiple even if we have no way to efficiently enumerate all the
states of the process.
What (9.2.1) says is that if we start in the stationary distribution and ob-
serve either a forward transition hX0 , X1 i or a backward transition hX1 , X0 i,
we cant tell which is which; Pr [X0 = i X1 = j] = Pr [X1 = i X0 = j].
This extends to longer sequences. The probability that X0 = i, X1 = j, and
X2 = k is given by i pij pjk = pji j pjk = pji pkj k , which is the probability
that X0 = k, X1 = j, and X0 = i. (A similar argument works for finite
sequences of any length.) So a reversible Markov chain is one with no arrow
of time in the stationary distribution.
A typical reversible Markov chain is a random walk on a graph, where
a step starting from a vertex u goes to one of its neighbors v, which each
1
neighbor chosen with probability d(u) . This has a stationary distribution
d(u)
u = P
u d(u)
d(u)
= ,
2|E|
CHAPTER 9. MARKOV CHAINS 150
which satisfies
d(u 1 d(v 1
u puv = = = v pvu .
2|E| d(u) 2|E| d(v)
If we dont know in advance, we can often guess it by observing that
i pij = j pji
implies
pij
j = i , (9.2.2)
pji
provided pij 6= 0. This gives us the ability to calculate k starting from any
initial state i as long as there is some chain of transitions i = i0 i1 i2
. . . i` = k where each step im im+1 has pim ,im+1 6= 0. For a random walk
on a graph, this implies that is unique as long as the graph is connected.
This of course only works for reversible chains; if we try to do this with a
non-reversible chain, we are likely to get a contradiction.
For example, if we consider a biased random walk on the n-cycle, which
moves from i to (i + 1) mod n with probability p and in the other direction
with probability q = 1 p, then applying (9.2.2) repeatedly would give
i
i = 0 pq . This is not a problem when p = q = 1/2, since we get i = 0
for all i and can deduce that i = 1/n is the unique stationary distribution.
But if we try it for p = 2/3, then we get i = 0 2i , which is fine up until we
hit 0 = n = 0 2n . So for p 6= q, this process is not reversible, which is not
surprising if we realize that the n = 60, p = 1 case describes precisely the
movement of the second hand on a clock.5
Reversible chains have a special role in Markov chain theory, because
some techniques for proving convergence only apply to reversible chains (see
9.4.4). They are also handy for sampling from large, irregular state spaces,
because by tuning the transition probabilities locally we can often adjust
the relative likelihoods of states in the stationary distribution to be closer to
what we want (see 9.2.7).
where the supremum is taken over all sets A for which Pr [X A] and
Pr [Y A] are both defined.6
An equivalent definition is
dT V (X, Y ) = sup|Pr [X A] Pr [Y A]|.
A
So dT V (x, y) = 12 kx yk1 .
means that for any > 0, there is a mixing time tmix () such that for any
initial distribution x and any t tmix (),
dT V (xP t , ) .
dT V (X, Y ) Pr [X 6= Y ] .
Pr [X A] = Pr [X A Y A] + Pr [X A Y 6 A] ,
Pr [Y A] = Pr [X A Y A] + Pr [X 6 A Y A] ,
and thus
Pr [X A] Pr [Y A] = Pr [X A Y 6 A] Pr [X 6 A Y A]
Pr [X A Y 6 A]
Pr [X 6= Y ] .
Since this holds for any particular set A, it also holds when we take the
maximum over all A to get dT V (X, Y ).
CHAPTER 9. MARKOV CHAINS 154
For Markov chains, our goal will be to find a useful coupling between a se-
quence of random variables X0 , X1 , X2 , . . . corresponding to the Markov chain
starting in an arbitrary distribution with a second sequence Y0 , Y1 , Y2 , . . .
corresponding to the same chain starting in a stationary distribution. What
will make a coupling useful is if Pr [Xt 6= Yt ] is small for reasonably large t:
since Yt has the stationary distribution, this will show that dT V (xP t , ) is
also small.
Our first use of this technique will be to show, using a rather generic
coupling, that Markov chains with certain nice properties converge to their
stationary distribution in the limit. Later we will construct specialized
couplings for particular Markov chains to show that they converge quickly.
the period of i is m, then we can only return to i at times that are multiples
of m. If m = 1, state i is said to be aperiodic. A Markov chain as a whole
is aperiodic if all of its states are aperiodic. In graph-theoretic terms, this
means that the graph of the chain is not k-partite for any k > 1. Reversible
chains are also an interesting special case: if a chain is reversible, it cant
have a period greater than 2, since we can always step off a node and step
back.
If our Markov chain is not aperiodic, we can make it aperiodic by flipping
a coin at each step to decide whether to move or not. This gives a lazy
Markov chain whose transition probabilities are given by 12 pij when i 6= j
and 12 + 12 pij when i = j. This doesnt affect the stationary distribution: if
CHAPTER 9. MARKOV CHAINS 155
Proof. Let S = {t | pii (t) 6= 0}. Since gcd(S) = 1, there is a finite subset S 0
of S such that gcd S 0 . Write the elements of S 0 as m1 , m2 , . . . , mk and let
M = kj=1 mj . From the extended Euclidean algorithm, there exist integer
Q
to use each aj as the number of times to go around the length mj loop from
i to i. Unfortunately many of these aj will be negative.
To solve this problem, we replace aj with bj = aj + M/mj . This makes all
the coefficients non-negative, and gives kj=1 bj mj = kM + 1. This implies
P
that ptii =
6 0 for any such t. But for larger t, we can just add in more copies
of M . So in fact ptii 6= 0 for all t t0 = (kM )2 .
Proof. Consider two copies of the chain {Xt } and {Yt }, where X0 starts in
some arbitrary distribution x and Y0 starts in a stationary distribution .
Define a coupling between {Xt } and {Yt } by the rule: (a) if Xt = 6 Yt , then
Pr [Xt+1 = j Yt+1 = j 0 | Xt = i Yt = i0 ] = pij pi0 j 0 ; and (b) if Xt = Yt ,
CHAPTER 9. MARKOV CHAINS 156
we sample random points from the original distribution until we find one for
which A holds), and Pr [i | A] is easy to compute for any fixed i but tricky
to compute for arbitrary events (so we cant use divide-and-conquer). If we
let f (i) Pr [i | A], then Metropolis-Hastings will do exactly what we want,
assuming it converges in a reasonable amount of time.
Let q be the transition probability for Q. Define, for i 6= j,
!
i f (j)
qij = pij min 1,
j f (i)
!
i j
= pij min 1,
j i
and let qii be whatever probability is left over. Now consider two states i
and j, and suppose that i f (j) j f (i). Then
qij = pij
which gives
i qij = i pij ,
while
j qji = j pji (j i /i j )
= pji (j i /i )
= i (pji j )/i
= i (pij i )/i
= i pij
Whichever way the first flip goes, we get Zt+1 = Zt 1 with equal
probability. So Z acts as an unbiased random walk on Zm with an absorbing
barriers at 0; this is equivalent to a random walk on 0 . . . m with absorbing
barriers at both endpoints. The expected time for this random walk to reach
a barrier starting from an arbitrary initial state is at most m2 /4, so if is
the first time at which X = Y , we have E [ ] m2 /4.7
Using Markovs inequality, after t = 2(m2 /4) = m2 /2 steps we have
Pr [Xt 6= Yt ] = Pr > m2 /2 mE[ ]
2 /2 1/2. We can also iterate the whole
argument, starting over in whatever state we are in at time t if we dont
converge. This gives at most a 1/2 chance of not converging for each interval
of m2 /2 steps. So after m2 /2 steps we will have Pr [Xt 6= Yt ] 2 . This
gives tmix () 12 m2 lg(2/), where as before tmix () is the time needed to
make dT V (Xt , ) (see 9.2.3).
The choice of 2 for the constant in Markovs inequality could be improved.
The following lemma gives an optimized version of this argument:
Lemma 9.3.1. Let the expected coupling time, at which two coupled pro-
cesses {Xt } and {Yt } starting from an arbitrary state are first equal, be T .
Then dT V (XT , YT ) for T T e ln(2/).
Its worth noting that the random walk example was very carefully rigged
to make the coupling argument clean. A similar argument still works (perhaps
with a change in the bound) for other ergodic walks on the ring, but the
details are messier.
9.3.3.1 Move-to-top
This is a variant of card shuffling that is interesting mostly because it gives
about the easiest possible coupling argument. At each step, we choose one
of the cards uniformly at random (including the top card) and move it to
the top of the deck. How long until the deck is fully shuffled, i.e., until the
total variation distance between the actual distribution and the stationary
distribution is bounded by ?
Here the trick is that when we choose a card to move to the top in the
X process, we choose the same card in the Y process. Its not hard to see
that this links the two cards together so that they are always in the same
position in the deck in all future states. So to keep track of how well the
coupling is working, we just keep track of how many cards are linked in this
way, and observe that as soon as n 1 are, the two decks are identical.
Note: Unlike some of the examples below, we dont consider two cards to
be linked just because they are in the same position. We are only considering
cards that have gone through the top position in the deck (which corresponds
to some initial segment of the deck, viewed from above). The reason is that
these cards never become unlinked: if we pick two cards from the initial
segment, the cards above them move down together. But deeper cards that
happen to match might become separated if we pull a card from one deck
that is above the matched pair while its counterpart in the other deck is
below the matched pair.
Having carefully processed the above note, given k linked cards the
probability that the next step links another pair of cards is exactly (n k)/n.
So the expected time until we get k + 1 cards is n/(n k), and if we sum
these waiting times for k = 0 . . . n 1, we get nHn , the waiting time for the
coupon collector problem. So the bound on the mixing time is the same as
for the random walk on a hypercube.
neither card i nor position xi is picked, i doesnt move, and so it stays linked.
If card i is picked, then both copies are moved to the same location; it stays
linked. If position xi is picked, then it may be that i becomes unlinked; but
this only happens if the card j that is picked has xj 6= yj . In this case j
becomes linked, and the number of linked cards doesnt drop.
Now we need to know how likely it is that we go from k to k + 1 linked
cards. Weve already seen a case where the number of linked cards increases;
we pick two cards that arent linked and a location that contains cards that
arent linked. The probability of doing this is ((n k)/n)2 , so our total
expected waiting time is n2 (n k)2 = n2 k 2 n 2 /6 (see http:
P P
1
3. For i 6 D, swap (i, i + 1) in the Y deck only with probability 2n .
|D|
4. Do nothing with probability 2n .
Its worth checking that the total probability of all these events is |D|/2n+
2(n |D|)/2n + |D|/2n = 1. More important is that if we consider only one
1
of the decks, the probability of doing a swap at (i, i + 1) is exactly 2n (since
we catch either case 1 or 2 for the X deck or 1 or 3 for the Y deck).
Now suppose that some card c is at position x in X and y in Y . If
x = y, then both x and x 1 are in D, so the only way the card can move
is if it moves in both decks: linked cards stay linked. If x = 6 y, then c
moves in deck X or deck Y , but not both. (The only way it can move
in both is in case 1, where i = x and i + 1 = y or vice verse; but in
this case i cant be in D since the copy of c at position x doesnt match
whatever is in deck Y , and the copy at position y doesnt match whats
in deck X.) In this case the distance x y goes up or down by 1 with
1
equal probability 2n . Considering x y (mod n), we have a lazy random
walk that moves with probability 1/n, with absorbing barriers at 0 and
n. The worst-case expected time to converge is n(n/2)2 = n3 /4, giving
Pr time for c to become linked n 3 /8 2 using the usual argument.
Now apply the union bound to get Pr time for every c to become linked n3 /8
throwing in a few extra nodes if some Zi , Zi+1 move away from each other),
we could also imagine that we start with a fresh path at each step and throw
it away as soon as it has done its job.
1. Neither c nor c0 are in T . Then X t+1 and Y t+1 are choosing a new
color from the same set, and we can make both choose the same color:
the distance between X and Y is unchanged.
picking each color in T \ {c}, which is what we want), and let Yut+1 = c
with probability 1` . Now the distance between X and Y increases with
probability 1` .
3. Both c and c0 are in T . For each c00 in T \ {c, c0 }, let Xut+1 = Yut+1 = c00
1
with probability `1 ; since there are ` 2 such c00 , this accounts for `2
`1
of the probability. Assign the remaining `1 1
to Xut+1 = c0 , Yut+1 = c.
In this case the distance between X and Y increases with probability
1
`1 , making this the worst case.
1
` k + 1, giving a maximum expected increase of n k . So
h i 1 1
E d(X t+1 , Y t+1 ) d(X t , Y t ) d(X t , Y t ) = 1 +
n n k
1
= 1 +
n k
1 (k ) +
=
n k
1 k 2
= .
n k
So we get
h i
dT V (X t , Y t ) Pr X t 6= Y t
1 k 2 t
h i
1 E d(X 0 , Y 0 )
n k
t k 2
exp n.
n k
For fixed k and with k > 2, this is e(t/n) n, which will be less than
for t = (n(log n + log(1/))).
When k = 2, it may be possible to use a variant of this argument to
prove convergence, since in this case the expected change in d(X, Y ) at each
step is at most 0, and it changes by 1 or more with probability (1/n). So we
might be able to argue that we have a random walk that is at worst unbiased
and at best biased in the direction we like. The convergence bound we would
get from this is not so goodO(n3 log(1/))but it is still polylogarithmic
in the size of the state space. However, there is an important step that needs
to be filled in to make this argument work: we need to show that a typical
expectation-0 random change in the length of one part of the path is not
exactly compensated for by perfectly anticorrelated expectation-0 change in
the length of another part of the path, and we havent done this. This issue
doesnt come up in standard path coupling because we dont mind if different
parts of the path are anticorrelated as long as they all shrink on average,
and indeed any anticorrelation just makes the shrinkage more predictable.
For k < 2, the argument collapses completely: its more likely than
not that X and Y move away from each other, so even if Xs distribution
converges to the stationary distribution, we wont see X and Y coalesce any
time soon using this particular coupling.
CHAPTER 9. MARKOV CHAINS 168
Single peak with very small amounts of noise Now well let g :
2n N be some arbitrary Lipschitz function, that is, a function with the
property that |g(x) g(y)| |x y|, and ask for what values of p = e
the Metropolis-Hastings walk with f (i) = eg(i) can be shown to converge
quickly. Given adjacent states x and y, with xi 6= yi but xj = yj for all
j 6= i, we still have a probability of at least (1 + p)/2n of coalescing the
states by setting xi = yi . But now there is a possibility that if we try to
move to (x[j/b], y[j/b]) for some j and b, that x rejects while y does not
or vice versa (note if xj = yj = b, we dont move in either copy of the
process). Conditioning on j and b, this occurs with probability 1 p precisely
when x[j/b] < x and y[j/b] y or vice versa, giving an expected increase in
|x y| of (1 p)/2n. We still get an expected net change of 2p/2n = p/n
provided there is only one choice of j and b for which this occurs. So we
converge in time () (n/p) log(n/) in this case.9
One way to think of this is that the shape of the neighborhoods of nearby
points is similar. If I go up in a particular direction from point x, its very
likely that I go up in the same direction from some neighbor y of x.
9
P You might reasonably ask if such functions g exist. One example is g(x) = (x1 x2 ) +
i>2
xi .
CHAPTER 9. MARKOV CHAINS 170
If there are more bad choices for j and b, then we need a much larger value
of p: the expected net change is now (k(1p)1p)/2n = (k1(k+1)p)/2n,
which is only negative if p > (k 1)/(k + 1). This gives much weaker pressure
towards large values of g, which still tends to put us in high neighborhoods
but creates the temptation to fiddle with to try to push us even higher
once we think we are close to a peak.
and
" #
h i p q h i h i
1 1 = p q q p = (p q) 1 1 .
q p
2 n
X
t
x
= 2t 2
i ci
2
i=2
n
X
2t 2
2 ci
i=2
n
X
= 2t
2 c2i
i=2
= 2 kx0
2t
k22 .
1
dT V (xt , ) = kxt k1
2
n t 0
kx k2
2 2
t2 n.
t
to get dT V (x , n) , we will need t ln(2 ) + ln
If we want n ln or
1 1
t ln(1/2) 2
ln n + ln(1/) .
1
The factor ln(1/ 2)
= ln1 2 can be approximated by 2 = 1
1
2
, which is
called the mixing rate or relaxation time of the Markov chain. Indeed,
our old friend 1 + x ex implies ln(1 + x) x, which
gives ln 2 2 1
1 1 1
and thus ln 2 12 = 2 . So 2 2 ln n + ln(1/) gives a conservative
estimate on the time needed to achieve dT V (xt , ) starting from an
arbitrary distribution.
Its worth comparing this to the mixing time tmix = arg mint dT V (xt , )
1/4 that we used with coupling. Here we have to throw in an extra factor of
1
2 ln n to get the bound down to 1, but after that the bound continues to drop
by a factor of e every 2 steps. In constrast, we have to go through another
tmix steps for each factor of 2 improvement in total variation distance, even
if the initial drop avoids the log factor. Since we cant always tell whether
coupling arguments or spectral arguments will do better for a particular
chain, and since convergence bounds are often hard to obtain no matter how
many techniques we throw at them, we will generally be happy with any
reasonable bound on either 2 or tmix .
1/2
q
i
ii = i , and Aij = j Pij . Then A is symmetric, because
s
i
Aij = Pij
j
s
i j
= Pji
j i
j
r
= Pji
i
= Aji .
9.4.4 Conductance
The conductance or Cheeger constant to (S) of a set S of states in a
Markov chain is
P
iS,j6Si pij
(S) = . (9.4.1)
(S)
This is the probability of leaving S on the next step starting from the
stationary distribution conditioned on being in S. The conductance is a
CHAPTER 9. MARKOV CHAINS 175
1 2 2 1 2 /2. (9.4.3)
Corollary 9.4.2.
1 2
2 2 . (9.4.4)
2
In other words, high conductance implies low relaxation time and vice
versa, up to squaring.
1 4|S|/n 1
(S) = .
8nm |S|/nm 2n
9.4.7 Congestion
For less symmetric chains, we weight paths by the probabilities of their
endpoints when counting how many cross each edge, and treat the flow
across the edge as a capacity. This gives the congestion of a collection of
canonical paths = {xy }, which is computed as
1 X
() = max x y ,
uvE u puv xy 3uv
2 82 . (9.4.6)
Proof. Pick some set of canonical paths with () = . Now pick some
ST partition with (S) = . Consider a flow where we route (x)(y) units
of flow along each path xy with x S and y T . This gives a total flow of
(S)(T ) (S)/2. We are going to show that we need a lot of capacity
across the ST cut to carry this flow, which will give the lower bound on
conductance.
For any ST edge uv, we have
1 X
x y
u puv xy 3uv
or
X
x y u puv .
xy 3uv
CHAPTER 9. MARKOV CHAINS 179
But then
P
uS,tT,uvE u puv
(S) =
S
(S)(T )/
(S)
(T )
=
1
.
2
9.4.8 Examples
Here are some more examples of applying the spectral method.
may leave St+1 = St if St already omitted e); otherwise, set St+1 = St {e}
unless one of the endpoints of e is already incident to an edge in St , in which
case set St+1 = St .
Because this chain contains many self-loops, its aperiodic. Its also
straightforward to show that any transition between two adjacent matchings
1
occurs with probability exactly 2m , where m = |E|, and thus that the chain
is reversible with a uniform stationary distribution. Wed like to bound the
congestion of the chain to show that it converges in a reasonable amount of
time.
Let N be the number of matchings in G, and let n = |V | and m = |E| as
usual. Then S = 1/N for all S and S pST = 2N1m . Our congestion for any
transition ST will then be 2N mN 2 = 2m/N times the number of paths
that cross ST ; ideally this number of paths will be at most N times some
small polynomial in n and/or m.
Suppose we are trying to get from some matching X to another matching
Y . The graph X Y has maximum degree 2, so each of its connected
components is either a path or a cycle; in addition, we know that the edges
in each of these paths or cycles alternate whether they come from X or Y ,
which among other things implies that the cycles are all even cycles.
We can transform X to Y by processing these components in a methodical
way: first order the components (say, by the increasing identity of the smallest
vertex in each), then for each component replace the X edges with Y edges.
If we do this cleverly enough, we can guarantee that for any transition ST ,
the set of edges (X Y ) \ (S T ) always consists of a matching plus at most
two extra edges, and that S, T , (X Y ) \ (S T ) are enough to reconstruct
X and Y . Since there are at most N m2 choices of (X Y ) \ (S T ), this
will give at most N m2 canonical paths across each transition.12
Here is how we do the replacement within a component. If C is a
cycle with k vertices, order the vertices v0 , . . . , vk1 such that v0 has the
smallest index in C and v0 v1 X. Then X C consists of the even-
numbered edges e2i = v2i v2+1 and Y C consists of the odd-numbered edges
e2i+1 = v2i+1 v2i+2 , where we take vk = v0 . We now delete e0 , then alternate
between deleting e2i and adding e2i1 for i = 1 . . . k/2 1. Finally we add
ek1 .
The number of edges in C at each step in this process is always one of
k/2, k/2 1, or k/2 2, and since we always add or delete an edge, the
number of edges in C (S T ) for any transition will be at least k/2 1,
which means that the total degree of the vertices in C (S T ) is at least
12 m
We could improve the constant a bit by using N 2
, but we wont.
CHAPTER 9. MARKOV CHAINS 182
The walk can be started from any perfect matching, which can be found
in O(n5/2 ) time using a classic algorithm of Hopcroft and Karp [HK73] that
repeatedly searches for an augmenting path, which is a path in G between
two unmatched vertices that alternates between edges not in the matching
and edges in the matching. (Well see augmenting paths again below when we
show that any near-perfect matching can be turned into a perfect matching
using at most two transitions.)
We can show that this walk converges in polynomial time using a canonical
path argument. This is done in two stages: first, we define canonical paths
between all perfect matchings. Next, we define a short path from any
matching of size n 1 to some nearby perfect matching, and build paths
between arbitrary matchings by pasting one of these short paths on one or
CHAPTER 9. MARKOV CHAINS 184
both ends of a long path between perfect matchings. This gives a collection
of canonical paths that we can show to have low congestion.
To go between perfect matchings X and Y , consider X Y as a collection
of paths and even cycles as in 9.4.8.3. In some standard order, fix each path
cycle by first deleting one edge to make room, then using rotate operations
to move the rest of the edges, then putting the last edge back in. For any
transition ST along the way, we can use the same argument that we can
compute X Y from S T by supplying the missing edges, which will consist
of a matching of size n plus at most one extra edge. So if N is the number
of matchings of size n or n 1, the same argument used previously shows
that at most N m of these long paths cross any ST transition.
For the short paths, we must use the density property. The idea is that for
any matching that is not perfect, we can find an augmenting path of length at
most 3 between two unmatched nodes on either side. Pick some unmatched
nodes u and v. Each of these nodes is adjacent to at least n/2 neighbors; if
any of these neighbors are unmatched, we just found an augmenting path
of length 1. Otherwise the n/2 neighbors of u and the n/2 nodes matched
to neighbors of v overlap (because v is unmatched, leaving at most n 1
matched nodes and thus at most n/21 nodes that are matched to something
thats not a neighbor of v). So for each matching of size n 1, in at most
two steps (rotate and then add an edge) we can reach some specific perfect
matching. There are at most m2 ways that we can undo this, so each perfect
matching is associated with at most m2 smaller matchings. This blows up
the number of canonical paths crossing any transition by roughly m4 ; by
counting carefully we can thus show congestion that is O(m6 ) (O(m4 ) from
the blow-up, m from the m in N m, and m from 1/pST ).
It follows that for this process, 2 = O(m12 ). (I think a better analysis is
possible.)
As noted earlier, this is an example of a process for which causal coupling
doesnt work in less than exponential time [KR99], a common problem with
Markov chains that dont have much symmetry. So its not surprising that
stronger techniques were developed specifically to attack this problem.
Chapter 10
Approximate counting
185
CHAPTER 10. APPROXIMATE COUNTING 186
i, we can cut this time to O(log n) such computations down using binary
search. The second step depends on whatever mechanism we use to unrank
within Ui .
An example would be generating one of the nk subsets of a set of size
element as their smallest element in some fixed ordering. But then we can
ni
easily compute |Si | = k=1 for each i, and apply the above technique to pick
a particular Si to start with and then recurse within Si to get the rest of the
elements.
A more general case is when we cant easily sample from U but we can
sample from some T U . Here rejection sampling comes to our rescue
CHAPTER 10. APPROXIMATE COUNTING 188
To make this concrete, lets look at the specific problem studied by Karp
and Luby of approximating the number of satisfying assignment to a DNF
CHAPTER 10. APPROXIMATE COUNTING 189
the union of any collection of sets Ui where we can (a) compute the size of
each Ui ; (b) sample from each Ui individually; and (c) test membership of
our sample x in Uj for j < i.
erty that prevents us from setting all the xi to zero). Well assume that the
ai and b are all integers.
For #KNAPSACK, we want to compute |S|, where S is the set of all
assignments to the xi that make ni=1 ai xi b.
P
knapsack problem, where we substitute a0i for ai and n2 = (n2 /b)b for b.
CHAPTER 10. APPROXIMATE COUNTING 191
Pn
Claim: S S 0 . Proof: ~x S if and only if i=1 ai xi b. But then
n n
a0i xi =
X X
bn2 ai /bcxi
i=1 i=1
n
X
(n2 /b)ai xi
i=1
n
X
= (n2 /b) ai xi
i=1
n2 ,
which shows ~x S 0 .
The converse does not hold. However, we can argue that any ~x S 0 can
be shoehorned into S by setting at most one of the xi to 0. Consider the
set of all positions i such that xi = 1 and ai > b/n. If this set is empty,
then ni=1 ai xi ni=1 b/n = b, and ~x is already in S. Otherwise, pick any
P P
subsets of {a01 , . . . , a0k } that sum to m or less. Then C(k, m) satisfies the
recurrence
10.5.1 Matchings
We saw in 9.4.8.3 that a random walk on matchings on a graph with m
edges has mixing time 2 8m6 , where the walk is defined by selecting an
edge uniformly at random and flipping whether it is in the matching or not,
while rejecting any steps that produce a non-matching. This allows us to
sample matchingsof a graph with total variation distance from the uniform
distribution in O m6 log m log 1 time.
Suppose now that we want to count matchings instead of sampling them.
Its easy to show that for any particular edge uv G, at least half of all
matchings in G dont include uv: the reason is that if M is a matching in G,
then M 0 = M \ {uv} is also a matching, and at most two matchings M 0 and
M 0 {uv} are mapped to any one M 0 by this mapping.
Order the edges of G arbitrarily as e1 , e2 , . . . , em . Let Si be the set of
matchings in G \ {e1 . . . ei }. Then S0 is the set of all matchings, and weve
just argued that i+1 = |Si+1 |/|Si | 1/2. We also know that |Sm | counts
the number of matchings in a graph with no edges, so its exactly one. So
|Si |
we can use the product-of-ratios trick to compute S0 = m
Q
i=1 |Si+1 | .
A random walk of length O 8m6 log m log 1 can sample matchings from
Si with a probability 0 of getting a matching in Si+1 that is between (1
)i+1 and (1+)i+1 . From Lemma 10.2.1, we canestimate 0 within relative
error with probability at least 1 using O 2 0 log = O 1 log 1
1 1
samples. Combined with the error on 0 ,this gives relative error at most
+ + in O m log m log 1 log 1 log 1 operations.1 If we then multiply
6
out all the estimates for |Si |/|Si+1 |, we get an estimate of S0 that is at most
(1+++)m times the correct value with probability at least 1m (with a
similar bound on the other side), in total time O m7 log m log 1 log 1 log 1 .
To turn this into a fully polynomial-time approximation scheme, given
1
This is the point where sensible people start hauling out the O notation, where a
(n)) if it O(f (n)g) where g is polylogarithmic in n and any other parameters
function is O(f
that may be running around ( 1 , 1 , etc.).
CHAPTER 10. APPROXIMATE COUNTING 194
The probabilistic method is a tool for proving the existence of objects with
particular combinatorial properties, by showing that some process generates
these objects with nonzero probability.
The relevance of this to randomized algorithms is that in some cases
we can make the probability large enough that we can actual produce such
objects.
Well mostly be following Chapter 5 of [MR95] with some updates for
more recent results. If youd like to read more about these technique, a
classic reference on the probabilistic method in combinatorics is the text of
Alon and Spencer [AS92].
195
CHAPTER 11. THE PROBABILISTIC METHOD 196
In each case, the probability that we get a good outcome is actually pretty
high, so we could in principle generate a good outcome by retrying our
random process until it works. There are some more complicated examples
of the method for which this doesnt work, either because the probability of
success is vanishingly small, or because we cant efficiently test whether what
we did succeeded (the last example below may fall into this category). This
means that we often end up with objects whose existence we can demonstrate
even though we cant actually point to any examples of them. For example,
it is known that there exist sorting networks (a special class of circuits
for sorting numbers in parallel) that sort in time O(log n), where n is the
number of values being sorted [AKS83]; these can be generated randomly
with nonzero probability. But the best explicit constructions of such networks
take time (log2 n), and the question of how to find an explicit network that
achieves O(log n) time has been open for over 25 years now despite many
efforts to solve it.
value of R(k, h) is known only for small values of k and h.3 But we can use
the probabilistic method to show that for k = h, it is reasonably large. The
following theorem is due to Erds, and was the first known lower bound on
R(k, k).
Proof. Suppose each pair of schoolchildren flip a fair coin to decide whether
they like each other or not. Then the probability that any particular set of
k
k schoolchildren all like each other is 2(2) and the probability that they all
hate each other is the same. Summing over both possibilities and all subsets
k
gives a bound of nk 21(2) on the probability that there is at least one subset
The last step in the proof uses the fact that 21+k/2 < k! for k 3, which
can be tested explicitly for k = 3 and proved by induction for larger k. The
resulting bound is a little bit weaker than just saying that n must be large
k
enough that nk 21(2) 1, but its easier to use.
value is at least 2n (n 1)!, there must be some specific outcome that gives
a value at least this high.
m/2 = E [X]
= (1 p) E [X | X < m/2] + p E [X | X m/2]
m1
(1 p) + pm.
2
Solving this for p gives the claimed bound.4
By running this enough times to get a good cut, we get a polynomial-time
randomized algorithm for approximating the maximum cut within a factor
of 2, which is pretty good considering that MAX CUT is NP-hard.
There exist better approximation algorithms. Goemans and Williamson [GW95]
give a 0.87856-approximation algorithm for MAX CUT based on randomized
rounding of a semidefinite program. We wont attempt to present this here,
but we will describe (in 11.2.2) an earlier result, also due to Goemans and
4
This is tight for m = 1, but I suspect its an underestimate for larger m. The
main source of slop in the analysis seems to be the step E [X | X m/2] m; using a
concentration bound, we should be able to show a much stronger inequality here and thus
a much larger lower bound on p.
CHAPTER 11. THE PROBABILISTIC METHOD 201
3
Williamson [GW94], that gives a 4 -approximation to MAX SAT using a
similar technique.
subject to X X
yi + (1 yi ) zj ,
iCj+ iCj
for all j.
The main trick here is to encode OR in the constraints; there is no
requirement that zj is the OR of the yi and (1 yi ) values, but we maximize
the objective function by setting it that way.
Sadly, solving integer programs like the above is NP-hard (which is not
surprising, since if we could solve this particular one, we could solve SAT).
But if we drop the requirements that yi , zj {0, 1} and replace them with
0 yi 1 and 0 zj 1, we get a linear programsolvable in polynomial
timewith an optimal value at least as good as the value for the integer
program, for the simple reason that any solution to the integer program is
also a solution to the linear program.
requirements that variables be integers; this will let us find a fractional solution that is
at least as good as the best integer solution, but might be undesirable because it tells us
to do something that is ludicrous in the context of our original problem, like only putting
half a passenger on the next plane.
Linear programming has an interesting history. The basic ideas were developed indepen-
dently by Leonid Kantorovich in the Soviet Union and George Dantzig in the United States
around the start of the Second World War. Kantorovichs work had direct relevance to
Soviet planning problems, but wasnt pursued seriously because it threatened the political
status of the planners, required computational resources that werent available at the
time, and looked suspiciously like trying to sneak a capitalist-style price system into the
planning process; for a fictionalized account of this tragedy, see [Spu12]. Dantzigs work,
which included the development of the simplex method for solving linear programs, had
a higher impact, although its publication was delayed until 1947 by wartime secrecy.
7
Randomized rounding was invented by Raghavan and Thompson [RT87]; the particular
application here is due to Goemans and Williamson [GW94].
CHAPTER 11. THE PROBABILISTIC METHOD 203
The problem now is that the solution to the linear program is likely to
be fractional: instead of getting useful 01 values, we might find out we are
supposed to make xi only 2/3 true. So we need one more trick to turn the
fractional values back into integers. This is the randomized rounding step:
given a fractional assignment yi , we set xi to true with probability yi .
So what does randomized rounding do to clauses? In our fractional
solution, a clause might have value zj , obtained by summing up bits and
pieces of partially-true variables. Wed like to argue that the rounded version
gives a similar probability that Cj is satisfied.
Suppose Cj has k variables; to make things simpler, well pretend that
Cj is exactly x1 x2 . . . xk . Then the probability that Cj is satisfied is
exactly 1 ki=1 (1 yi ). This quantity is minimized subject to ki=1 yi zj
Q P
The second-to-last step looks like a typo, but it actually works. The idea
is to observe that the function f (z) = 1 (1 z/k)k is concave (Proof:
d2
dz 2
f (z) = k1
k (1 z/k)
k2 < 0), while g(z) = z(1 (1 1/k)k ) is linear,
different assignments), but we can run both in parallel and take whichever
gives a better result.
To show that this works, let Xj be indicator for the event that clause j is
satisfied by the randomized-rounding algorithm and Yj the indicator for the
even that it is satisfied by the simple algorithm. Then if Cj has k literals,
long as each event A occurs with positive probability. But most of the time,
well find that the events we care about arent independent, so this wont
work either.
The Lovsz Local Lemma [EL75] handles a situation intermediate
between these two extremes, where events are generally not independent of
each other, but each collection of events that are not independent of some
particular event A has low total probability. In the original version; its
non-constructive: the lemma shows a nonzero probability that none of the
events occur, but this probability may be very small if we try to sample
the events at random and there is no guidance for how to find a particular
outcome that makes all the events false.
Subsequent work [Bec91, Alo91, MR98, CS00, Sri08, Mos09, MT10]
showed how, when the events A are determined by some underlying set
of independent variables and independence between two events is detected
by having non-overlapping sets of underlying variables, an actual solution
could be found in polynomial expected time. The final result in this series,
due to Moser and Tardos [MT10], gives the same bounds as in the original
non-constructive lemma, using the simplest algorithm imaginable: whenever
some bad event A occurs, squish it by resampling all of its variables, and
continue until no bad events are left.
then
" #
A
\ Y
Pr (1 xA ). (11.3.2)
AA AA
8
This version is adapted from [MT10].
CHAPTER 11. THE PROBABILISTIC METHOD 206
In particular, this means that the probability that none of the Ai occur
is not zero, since we have assumed xAi < 1 holds for all i.
The role of xA in the original proof is to act as an upper bound on the
probability that A occurs given that some collection of other events doesnt
occur. For the constructive proof, the xA are used to show a bound on the
number of resampling steps needed until none of the A occur.
Proof. Basically, we are going to pick a single value x such that xA = x for
all A in A, and (11.3.1) is satisfied. This works as long as p x(1 x)d ,
d |(A)| =
as in for all A, Pr [A] p x(1 x) x(1 x)
Qthis case we have,
xA B(A) (1 xB ) .
d
For fixed d, x(1 x)d is maximized using the usual trick: dx x(1 x)d =
d d1 1
(1 x) xd(1 x) = 0 gives (1 x) xd = 0 or x = d+1 . So now we
d d
1 1 1
need p d+1 1 d+1 . It is possible to show that 1/e < 1 d+1 for
all d 0 (see the solution to Problem D.1.4). So ep(d + 1) 1 implies p
d
1
e(d+1) 1 1
d+1
1
d+1 x(1 x)|(A)| as required by Lemma 11.3.1.
11.3.3 Applications
11.3.3.1 Graph coloring
Lets start with a simple application of the local lemma where we know what
the right answer should be. Suppose we want to color the vertices of a cycle
with c colors, so that no edge has two endpoints with the same color. How
many colors do we need?
Using brains, we can quickly figure out that c = 3 is enough. Without
brains, we could try coloring the vertices randomly: but in a cycle with n
vertices and n edges, on average n/c of the edges will be monochromatic,
since each edge is monochromatic with probability 1/c. If these bad events
were independent, we could argue that there was a (1 1/c)n > 0 probability
CHAPTER 11. THE PROBABILISTIC METHOD 207
that none of them occurred, but they arent, so we cant. Instead, well use
the local lemma.
The set of bad events A is just the set of events Ai = [edge i is monochromatic].
Weve already computed p = 1/c. To get d, notice that each edge only shares
a vertex with two other edges, so |(Ai )| 2. Corollary 11.3.2 then says that
there is a good coloring as long as ep(d + 1) = 3e/c 1, which holds as long
as c 9. Weve just shown we can 9-color a cycle. If we look more closely
2
at the proof of Corollary 11.3.2, we can see that p 31 1 31 = 27 4
would
also work; this says we can 7-color a cycle. Still not as good as what we can
do if we are paying attention, but not bad for a procedure that doesnt use
the structure of the problem much.
When |S| = 0, this just says Pr [A] xA , which follows immediately from
(11.3.1).
For larger S, split S into S1 = S (A), the events in S that might
not be independent of A; and S2 = S \ (A), the events in S that we know
to be independent of A. If S2 = S, then A is independent
h T iof all events
in S, and (11.3.3) follows immediately from Pr A BS B = Pr [A]
Pr [A C1 | C2 ] Pr [A | C2 ]
= Pr [A]
Y
xA (1 xB ) , (11.3.5)
B(A)
from (11.3.1) and the fact that A is independent of all B in S2 and thus of
C2 .
T
For the denominator, we expand C1 backh out to BSi1 B and break
out the induction hypothesis. To bound Pr
T
B C2 , we order S1
BS1
arbitrarily as {B1 , . . . , Br }, for some r, and show by induction on ` as ` goes
from 1 to r that
" ` # `
i C2
\ Y
Pr B (1 xBi ). (11.3.6)
i=1 i=1
where the second-to-last step uses the outer induction hypothesis (11.3.3)
for the first term and the inner induction hypothesis (11.3.6) for the rest.
This completes the proof of the inner induction.
When ` = r, we get
" r #
i C2
\
Pr [C1 | C2 ] = Pr B
i=1
Y
(1 xB ). (11.3.7)
BS1
xA .
This completes the proof of the outer induction.
To get the bound (11.3.2), we reach back inside the proof and repeat
the argument for (11.3.7) with AA A in place of C1 and without the
T
For the base case we have k = 0 and Pr [] 1, using the usual conventions
on empty products. For larger k, we have
" k
i k1
#
h
Ai = Pr Ak Ai
\ \
Pr
i=1 i=1
k1
Y
(1 xAk ) (1 xAi )
i=1
k
Y
(1 xAk ),
i=1
where in the second-to-last step we use (11.3.3) for the first term and (11.3.8)
for the big product.
Setting k = n finishes the proof.
We defer the proof of Lemma 11.3.3 for the moment. For most applica-
tions, the following symmetric version is easier to work with:
How this expected m/d bound translates into actual time depends on
the cost of each resampling step. The expensive part at each step is likely to
be the cost of finding an A that occurs and thus needs to be resampled.
Intuitively, we might expect the resampling to work because if each A A
has a small enough neighborhood (A) and a low enough probability, then
whenever we resample As variables, its likely that we fix A and unlikely
that we break too many B events in As neighborhood. It turns out to be
tricky to quantify how this process propagates outward, so the actual proof
uses a different idea that essentially looks at this process in reverse, looking
for each resampled event A at a set of previous events whose resampling we
can blame for making A occur, and then showing that this tree (which will
include every resampling operation as one of its vertices) cant be too big.
The first step is to fix some strategy for choosing which event A to
resample at each step. We dont care what this strategy is; we just want
it to be the case that the sequence of events depends only on the random
choices made by the algorithm in its initial sampling and each resampling.
We can then define an execution log C that lists the sequence of events
C1 , C2 , C3 , . . . that are resampled at each step of the execution.
From C we now construct a witness tree Tt for each resampling step
t whose nodes are labeled with events, with the property that the children
of a node v labeled with event Av are labeled with events in + (Av ) =
{Av } (Av ). The root of Tt is labeled with Ct ; to construct the rest of
the tree, we work backwards through Ct1 , Ct2 , . . . , C1 , and for each event
Ci we encounter we attach Ci as a child of the deepest v we can find with
Ci + (Av ), choosing arbitrarily if there is more than one such v, and
discarding Ci if there is no such v.
Now we can ask what the probability is that we see some particular
witness tree T in the execution log. Each vertex of T corresponds to some
event Av that we resample because it occurs; in order for it to occur, the
previous assignments of each variable in vbl(Av ) must have made Av true,
which occurs with probability Pr [Av ]. But since we resample all the variables
in Av , any subsequent assignments to these variables are independent of the
CHAPTER 11. THE PROBABILISTIC METHOD 212
Pr [B] x0B .
For each vertex v in T , let Wv + (Av ) be the set of events B + (Av )
that dont occur as labels of children of v. The probability of getting T is
equal to the product of the probabilities at each v of getting all of its children
and none of its non-children. The non-children of v collectively contribute
BWv (1 xB ) to the product, and v itself contributes xAv (via the product
Q
for its parent), unless v is the root node. So we can express the giant product
as
1 Y Y
pT = xAv (1 xB ) .
xA vT BW v
We dont like the Wv very much, so we get rid of them by pushing a (1 xAv )
up from each vertex v, which we compensate for by dividing by 1 xAv at v
CHAPTER 11. THE PROBABILISTIC METHOD 213
1 xA Y 0
= xAv .
xA vT
Now we can bound the expected number of trees rooted at A that appear
in C, assuming (11.3.1) holds. Letting TA be the set of all such trees and
NA the number that appear in C, we have
X
E [NA ] = Pr [T appears in C]
T TA
X Y
Pr [A(v)]
T TA vT
x0Av
X Y
T TA vT
X xA
= pT
T TA
1 xA
xA X
= pT
1 xA T T
A
xA
.
1 xA
And were done.
Chapter 12
Derandomization
1. Reduce the number of random bits used down to O(log n), and then
search through all choices of random bits exhaustively. For example, if
we only need pairwise independence, we could use the XOR technique
from 5.1.2.1 to replace a large collection of variables with a small
collection of random bits.
Except for the exhaustive search part, this is how randomized algo-
rithms are implemented in practice: rather than burning random bits
continuously, a pseudorandom generator is initialized from a seed
consisting of a small number of random bits. For pretty much all of
the randomized algorithms we know about, we dont even need to use
a particularly strong pseudorandom generator. This is largely because
1
The class RP consists of all languages L for which there is a polynomial-time random-
ized algorithm that correctly outputs yes given an input x in L with probability at least
1/2, and never answers yes given an input x not in L. See 1.4.2 for a more extended
description of RP and other randomized complexity classes.
214
CHAPTER 12. DERANDOMIZATION 215
Proof. The intuition is that if any one random string has a constant proba-
bility of making M happy, then by choosing enough random strings we can
make the probability that M fails using on every random string for any given
input so small that even after we sum over all inputs of a particular size,
the probability of failure is still small using the union bound (4.1.1). This is
an example of probability amplification, where we repeat a randomized
algorithm many times to reduce its failure probability.
Formally, consider any fixed input x of size n, and imagine running M
repeatedly on this input with n + 1 independent sequences of random bits
r1 , r2 , . . . , rn+1 . If x 6 L, then M (x, ri ) never outputs 1. If x L, then for
each ri , there is an independent probability of at least 1/2 that M (x, ri ) = 1.
So Pr [M (x, ri ) = 0] 1/2, and Pr [iM (x, ri ) = 0] 2(n+1) . If we sum
this probability of failure for each individual x L of length n over the at
most 2n such elements, we get a probability that any of them fail of at most
CHAPTER 12. DERANDOMIZATION 217
The classic version of this theorem shows that anything you can do with
a polynomial-size randomized circuit (a circuit made up of AND, OR, and
NOT gates where some of the inputs are random bits, corresponding to the r
input to M ) can be done with a polynomial-size deterministic circuit (where
now the pn input is baked into the circuit, since we need a different circuit
for each size n anyway).
A limitation of this result is that ordinary algorithms seem to be better
described by uniform families of circuits, where there exists a polynomial-
time algorithm that, given input n, outputs the circuit Cn for processing size-n
inputs. In contrast, the class of circuits generated by Adlemans theorem
is most likely non-uniform: the process of finding the good witnesses ri is
not something we know how to do in polynomial time (with the usual caveat
that we cant prove much about what we cant do in polynomial time).
random to one side of the cut or the other, each edge appears in the cut with
probability 1/2, giving a total of m/2 edges in the cut in expectation.
Suppose that we replace these n independent random bits with n pairwise-
independent bits generated by taking XORs of subsets of dlg(n + 1)e inde-
pendent random bits as described in 5.1.2.1. Because the bits are pairwise-
independent, the probability that the two endpoints of an edge are assigned
to different sides of the cut is still exactly 1/2. So on average we get m/2
edges in the cut as before, and there is at least one sequence of random bits
that guarantees a cut at least this big.
But with only dlg(n+1)e random bits, there are only 2dlog(n+1)e < 2(n+1)
possible sequences of random bits. If we try all of them, then we find a cut
of size m/2 always. The total cost is O(n(n + m)) if we include the O(n + m)
cost of testing each cut. Note that this algorithm does not generate all 2n
possible cuts, but among those it does generate, there must be a large one.
In this particular case, well see below how to get the same result at a
much lower cost, using more knowledge of the problem. So we have the
typical trade-off between algorithm performance and algorithm designer
effort.
a subset is bad in O(k) time: if it already has both a present and missing
edge, its not bad. Otherwise, if weve already set ` of its edges to the
same value, its bad with probability exactly 2k+` . Summing this over all
O(nk ) subsets takes
O(nk k) time 2
per edge, and we have O(n ) edges, giving
O(nk+2 k) = O n(2 lg n+2+lg lg n) = nO(log n) time total.
Its worth mentioning that there are better deterministic constructions
in the literature. The best construction that I am aware of is given by an
c
algorithm of Barak et al. [BRSW06], which constructs a graph with k log k
vertices with no clique or independent set of size k for any fixed c.
1. For any edge that already has both endpoints assigned to S or T , its
either in the cut or it isnt: add 0 or 1 as appropriate to the conditional
expectation.
2. For any edge with only one endpoint assigned, theres a 1/2 probability
that the other endpoint gets assigned to the other side (in the original
randomized algorithm). Add 1/2 to the conditional expectation for
these edges.
3. For any edge with neither endpoint assigned, we again have a 1/2
probability that it crosses the cut. Add 1/2 for these as well.
the greedy algorithm achieves a cut of size m/2, which might require actual
intelligence to prove otherwise.
Pr [|Xj | > t | 1 , . . . , k ] = 1 Pr [t ` Y t `]
t`
!
X r r
= 2 .
i=t`
i
This last expression involves a linear number of terms, each of which we can
calculate using a linear number of operations on rational numbers that fit
in a linear number of bits, so we can calculate the probability exactly in
polynomial time by just adding them up.
For our pessimistic estimator, we take
n
X h i
U (1 , . . . , k ) = Pr |Xj | > 2n ln 2m 1 , . . . , k .
i=j
Note that we can calculate each term in the sum by adding up a big pile of
binomial coefficients. Furthermore, since each term in the sum is a Doob mar-
tingale, the sum is a martingale as well, so E [U (1 , . . . , k+1 ) | 1 , . . . , k ] =
U (1 , . . . , k ). It follows that for any choice of 1 , . . . , k there exists some
k+1 such that U (1 , . . . , k ) U (1 , . . . , k+1 ), and we can determine this
winning k+1 explicitly. Our previous argument shows that U (hi) < 1, which
implies that our final value U (1 , . . . , n ) will also be less than 1. Since U
is an integer,
this means it must be 0, and we find an assignment in which
|Xj | < 2n ln 2m for all j.
Chapter 13
Quantum computing
Any such state vector x for the system must consist of non-negative
real values that sum to 1; this is just the usual requirement for a discrete
222
CHAPTER 13. QUANTUM COMPUTING 223
probability space. Operations on the state consist of taking the old values of
one or both bits and replacing them with new values, possibly involving both
randomness and dependence on the old values. The law of total probability
applies here, so we can calculate the new state vector x0 from the old state
vector x by the rule
These are linear functions of the previous state vector, so we can summarize
the effect of our operation using a transition matrix A, where x0 = Ax.1
For example, if we negate the second bit 2/3 of the time while leaving
the first bit alone, we get the matrix
1/3 2/3 0 0
2/3 1/3 0 0
A= .
0 0 1/3 2/3
0 0 2/3 1/3
One way to derive this matrix other than computing each entry directly is
that it is the tensor product of the matrices that represent the operations
on each individual bit. The idea here is that the tensor product of A and B,
written A B, is the matrix C with Cij,k` = Aik Bj` . Were cheating a little
bit by allowing the C matrix to have indices consisting of pairs of indices,
one for each of A and B; there are more formal definitions that justify this
at the cost of being harder to understand.
In this particular case, we have
1/3 2/3 0 0 " # " #
2/3 1/3 0 0 1 0 1/3 2/3
= .
0 0 1/3 2/3 0 1 2/3 1/3
0 0 2/3 1/3
The first matrix in the tensor product gives the update rule for the first bit
(the identity matrixdo nothing), while the second gives the update rule for
the second.
1
Note that this is the reverse of the convention we adopted for Markov chains in
Chapter 9. There it was convenient to have Pij = pij = Pr [Xt+1 = j | Xt = i]. Here we
defer to the physicists and make the update operator come in front of its argument, like
any other function.
CHAPTER 13. QUANTUM COMPUTING 224
Some operations are not decomposable in this way. If we swap the values
of the two bits, we get the matrix
1 0 0 0
0 0 1 0
S= ,
0 1 0 0
0 0 0 1
xout = ASAxin
1/3 2/3 0 0 1 0 0 0 1/3 2/3 0 0 1
2/3 1/3 0 0 0
0 1 0 2/3 1/3 0
0 0
=
0 0 1/3 2/3 0 1 0 0 0 0 1/3 2/3 0
0 0 0 0 0
maps |10i to |01i (Proof: |01i h10| |10i = |01i h10|10i = |01i) and sends all
other states to 0. Add up four of these mappings to get
1 0 0 0
0 0 1 0
S = |00i h00| + |10i h01| + |01i h10| + |11i h11| = .
0 1 0 0
0 0 0 1
Here the bra-ket notation both labels what we are doing and saves writing a
lot of zeros.
p0 |0i + p1 |1i ,
a0 |0i + a1 |1i ,
where a0 and a1 are complex numbers with |a0 |2 + |a1 |2 = 1.2 The reason for
this restriction on amplitudes is that if we measure a qubit, we will see state 0
with probability |a0 |2 and state 1 with probability |a1 |2 . Unlike with random
bits, these probabilities are not mere expressions of our ignorance but arise
through a still somewhat mysterious process from the more fundamental
amplitudes.3
With multiple bits, we get amplitudes for all combinations of the bits,
e.g.
1
(|00i + |01i + |10i + |11i)
2
gives a state vector in which each possible measurement will be observed
2
1
with equal probability 2 = 14 . We could also write this state vector as
1/2
1/2
.
1/2
1/2
2
The absolute value, norm, or magnitude |a + bi| of a complex number is given by
a2 + b2 . When b = 0, this is the same as the absolute value for the corresponding
real
number. For any complex number x, the norm p can also be written
p as x x, where
x
is
the complex conjugate of x. This is because (a + bi)(a bi) = a2 (bi)2 = a2 + b2 .
The appearance of the complex conjugate here explains why we define hx|yi = x y; the
conjugate transpose means that for hx|xi, when we multiply xi by xi we are computing a
squared norm.
3
In the old days of shut up and calculate, this process was thought to involve the
unexplained power of a conscious observer to collapse a superposition into a classical
state. Nowadays the most favored explanation involves decoherence, the difficulty of
maintaining superpositions in systems that are interacting with large, warm objects with lots
of thermodynamic degrees of freedom (measuring instruments, brains). The decoherence
explanation is particularly useful for explaining why real-world quantum computers have a
hard time keeping their qubits mixed even when nobody is looking at them. Decoherence by
itself does not explain which basis states a system collapses to. Since bases in linear algebra
are pretty much arbitrary, it would seem that we could end up running into a physics
version of Goodmans grue-bleen paradox [Goo83], but there are ways of dealing with this
too (einselection). Since all of this is (a) well beyond my own limited comprehension of
quantum mechanics and (b) irrelevant to the theoretical model we are using, these issues
will not be discussed further.
CHAPTER 13. QUANTUM COMPUTING 228
If we apply H in parallel to all the qubits in our system, we get the n-fold
tensor product H n , which (if we take our bit-vector indices
q as integers
1
0 . . . N 1 = 2n 1 represented in binary) maps |0i to N1 N i=0 |ii. So
P
0 0 1 0
which is clearly unitary (the rows are just the standard basis vectors). We
could also write this more compactly as |00i h00| + |01i h01| + |11i h10| +
|10i h11|.
The CNOT operator gives us XOR, but for more destructive operations
we need to use more qubits, possibly including junk qubits that we wont look
at again but that are necessary to preserve reversibility. The Toffoli gate or
controlled controlled NOT gate (CCNOT) is a 3-qubit gate that was
originally designed to show that classical computation could be performed
reversibly [Tof80]. It implements the mapping (x, y, z) 7 (x, y, (x y) z),
CHAPTER 13. QUANTUM COMPUTING 230
0 0 0 0 0 0 1 0
2. We can represent f (x) by changing the phase of |xi: |xi 7 (1)f (x) |xi.
The actual unitary operator corresponding to this is x (1)f (x) |xi hx|,
P
0 0 0 1
5
In the case of fan-out, this only works with perfect accuracy for classical bits and not
superpositions, which run into something called the no-cloning theorem. For example,
applying CCNOT to 12 |010i + 12 |110i yields 12 |010i + 12 |111i. This works, sort of,
but the problem is that the first and last bits are still entangled, meaning we cant operate
on them independently. This is actually not all that different from what happens in the
probabilistic case (if I make a copy of a random variable X, its correlated with the original
X), but it has good or bad consequences depending on whether you want to prevent people
from stealing your information undetected or run two copies of a quantum circuit on
independent replicas of a single superposition.
CHAPTER 13. QUANTUM COMPUTING 231
The first representation makes more sense for modeling classical circuits.
The second turns out to be more useful when f is a subroutine in a larger
quantum algorithm. Fortunately, the operator with matrix
" #
1 0
0 1
Our goal is for this final state to tell us what we want to know, with
reasonably high probability.
6
Current technology, sadly, still puts quantum computing mostly in the science fiction
category.
CHAPTER 13. QUANTUM COMPUTING 232
Making this work requires showing that (a) we can generate the original
superposition |si, (b) we can implement D efficiently using unitary operations
on a constant number of qubits each, and (c) we actually get w at the end
of this process.
unitary. Compute
Here we use the fact that |si hs| |si hs| = |si hs|si hs| = |si (1) hs| = |si hs|.
Recall that |si = H n |0n i, where H n is the result of applying H to
each of the n bits individually. We also have that H = H and HH = I,
from which H n H n = I as well.
So we can expand
D = 2 |si hs| I
= 2H n |0n i (H n |0n i) I
= 2H n |0n i h0n | H n I
= H n (2 |0n i h0n | I) H n .
D = 2 |si hs| I
= 2 ((sin ) |wi + (cos ) |ui) ((sin ) hw| + (cos ) hu|) I
= (2 sin2 1) |wi hw| + (2 sin cos ) |wi hu| + (2 sin cos ) |ui hw| + (2 cos2 1) |ui hu|
= ( cos 2) |wi hw| + (sin 2) |wi hu| + (sin 2) |ui hw| + (cos 2) |ui hu|
" #
cos 2 sin 2
= ,
sin 2 cos 2
Ideally, we pick t so that (2t + 1) = /2, which would put all of the
amplitude on |wi. Because t is an integer, we cant do this exactly, but
CHAPTER 13. QUANTUM COMPUTING 236
setting t = b /21
2 c will get us somewhere between /2 2 and /2. Since
q
1
N,this gives us a probability of seeing |wi in our final measurement
p
of 1 O( 1/N ) after O( N ) iterations of Uw D.
Sadly, this is as good as it gets. A lower bound of Bennet et al. [BBBV97]
shows that any quantum algorithm using Uw as the representation for f must
apply Uw at least ( N ) times to find w. So we get a quadratic speedup
but not the exponential speedup wed need to solve NP-complete problems
directly.
Appendix A
Assignments
1. Your name.
237
APPENDIX A. ASSIGNMENTS 238
3. Whether you are taking the course as CPSC 469 or CPSC 569.
(You will not be graded on the bureaucratic part, but you should do it
anyway.)
1 procedure BubbleSortOnePass(A, n)
2 for i 1 to n 1 do
3 if A[i] > A[i + 1] then
4 Swap A[i] and A[i + 1]
Solution
The answer is n Hn , where Hn = ni=1 1i is the n-th harmonic number.
P
There are a couple of ways to prove this. Below, we let Ai represent the
original contents of A[i], before doing any swaps. In each case, we will use the
fact that after i iterations of the loop, A[i] contains the largest of Ai , . . . , Ai ;
this is easily proved by induction on i.
Let Xij be the indicator variable for the event that Ai is eventually
swapped with Aj . For this to occur, Ai must be bigger than Aj , and
must be present in A[j 1] after j 1 passes through the loop. This hap-
pens if and only if Ai is the largest value in A1 , . . . , Aj . Because these
APPENDIX A. ASSIGNMENTS 239
Alternatively, lets count how many values are not swapped from A[i]
to A[i 1]. We can then subtract from n to get the number that are.
Let Yi be the indicator variable for the event that Ai is not swapped
into A[i 1]. This occurs if, when testing A[i 1] against A[i], A[i] is
larger. Since we know that at this point A[i 1] is the largest value
among A1 , . . . , Ai1 , Yi = 1 if and only if Ai is greater than all of
A1 , . . . , Ai1 , or equivalently if Ai is the largest value in A1 , . . . , Ai .
Again by symmetry we have E [Yi ] = 1i , and summing over all i gives
an expected Hn values that are not swapped down. So there are n Hn
values on average that are swapped down, which also gives the expected
number of swaps.
APPENDIX A. ASSIGNMENTS 240
1. The students enter the room one at a time. No student enters until
the previous student has found a seat.
Solution
Define the i-th student to be the student who takes their seat after i students
have already sat (note that we are counting from zero here, which makes
things a little easier). Let Xi be the indicator variable for the even that the
i-th student does not find a seat on their own and needs help from a USA.
Each attempt to find a seat fails with probability i/m. Since each attempt is
independent of the others, the probability that all k attempts fail is (i/m)k .
The number of students who need help is n1
P
i=0 Xi , so the expected
1
An earlier version of this problem allowed k to grow with n, which causes some trouble
with the asymptotics.
APPENDIX A. ASSIGNMENTS 241
number is
"n1 # n1
X X
E Xi = E [Xi ]
i=0 i=0
n1
X
= (i/m)k
i=0
n1
k
X
=m ik .
i=0
k
I like writing this as n (n/m)
k+1 to emphasize that the cost per student
(n/m)k
is k+1 , but there are a lot of different ways to write the same thing.
Note that since we are dealing with asymptotics, we could also replace the
1 1
k+1 with just k and still be correct, but that seems less informative somehow.
days.
Our automated financial reporter will declare a dead cat bounce if a
stock falls in price for two days in a row, followed by rising in price, followed
by falling in price again. Formally, a dead cat bounce occurs on day i if
i 4 and Si4 > Si3 > Si2 < Si1 > Si . Let D be the number of dead
cat bounces over the n days.
1. What is E [D]?
3. Our investors will shut down our system if it doesnt declare at least
one dead cat bounce during the first n days. What upper bound you
can get on Pr [D = 0] using Chebyshevs inequality?
Note added 2016-09-28: Its OK if your solutions only work for sufficiently
large n. This should save some time dealing with weird corner cases when n
is small.
APPENDIX A. ASSIGNMENTS 243
Solution
1. Let Di be the indicator variable for the event that a dead cat bounce
occurs on day i. Let p = E [Di ] = Pr [Di = 1]. Then
1
p = Pr [Xi3 = 1 Xi2 = 1 Xi1=+1 Xi = 1] = ,
16
since the Xi are independent.
Then
" n #
X
E [D] = E Di
i=4
n
X
= E [Di ]
i=4
n
X 1
=
i=4
16
n3
= ,
16
assuming n is at least 3.
15
2. For variance, we cant just sum up Var [Di ] = p(1 p) = 256 , because
the Di are not independent. Instead, we have to look at covariance.
Each Di depends on getting a particular sequence of four values for
Xi3 , Xi2 , Xi1 , and Xi . If we consider how Di overlaps with Dj for
j > i, we get these cases:
Variable Pattern Correlation
Di --+-
Di+1 --+- inconsistent
Di+2 --+- inconsistent
Di+3 --+- overlap in one place
For larger j, there is no overlap, so Di and Dj are independent for
j 4, giving Cov [Di , Dj ] = 0 for these cases.
Because Di cant occur with Di+1 or Di+2 , when j {i + 1, i + 2} we
have
4. Here is an upper bound that avoids the mess of computing the exact
probability, but is still exponentially small in n. Consider the events
[D4i = 1] for i {1, 2, . . . , bn/4c}. These events are independent
since they are functions of non-overlapping sequences of increments.
So we can compute Pr [D = 0] Pr [D4i = 0, i {1, . . . , bn/4c}] =
(15/16)bn/4c .
This expression is a little awkward, so if we want to get an asymptotic
estimate we can simplify it using 1 + x ex to get (15/16)bn/4c
exp((1/16)bn/4c) = O(exp(n/64)).
APPENDIX A. ASSIGNMENTS 245
Solution
Well adapt QuickSort. If the bad comparisons occurred randomly, we could
just take the majority of (log n) faulty comparisons to simulate a non-faulty
comparison with high probability. But the adversary is watching, so if we do
these comparisons at predictable times, it could hit all (log n) of them and
stay well within its fault budget. So we are going to have to be more sneaky.
Heres this idea: Suppose we have a list of n comparisons hx1 , y1 i , hx2 , y2 i , . . . , hxn , yn i
that we want to perform. We will use a subroutine that carries out these
comparisons with high probability by doing kn ln n+n possibly-faulty compar-
isons, with k a constant to be chosen below, where each of the possibly-faulty
comparisons looks at xr and yr where each r is chosen independently and uni-
formly at random. The subroutine collects the results of these comparisons
for each pair hxi , yi i and takes the majority value.
At most n of these comparisons are faulty, and we get an error only if
some pair hxi , yi i gets more faulty comparisons than non-faulty ones. Let Bi
be the number of bad comparisons of the pair hxi , yi i and Gi the number of
good comparisons. We want to bound the probability of the event Bi > Gi .
The probability that any particular comparison lands on a particular
APPENDIX A. ASSIGNMENTS 246
Figure A.1: Filling a screen with Space Invaders. The left-hand image places
four copies of a 46-pixel sprite in random positions on a 40 40 screen. The
right-hand image does the same thing with 24 copies.
that this choice of ` does in fact get 1/2 o(1) of the pixels set with high
probability.
Solution
We will apply the following strategy. First, well choose ` so that each
individual pixel is set with probability close to 1/2. Linearity of expectation
then gives roughly n2 /2 total pixels set on average. To show that we get
close to this number with high probability, well use the method of bounded
differences.
The probability that pasting in a single copy of the sprite sets a particular
pixel is exactly m/n2 . So the probability that the pixel is not set after ` sprites
ln(1/2)
is (1 m/n2 )` . This will be exactly 1/2 if ` = log1m/n2 1/2 = ln(1m/n 2) .
Since ` must be an integer, we can just round this quantity to the nearest
integer to pick our actual `. For example, when n = 40 and m = 46,
ln(1/2)
ln(146/402 )
= 23.7612... which rounds to 24.
For large n, we can use the approximation ln(1 + x) x (which holds for
small x) to approximate ` as (n2 ln 2/m) + o(1). We will use this to get a
concentration bound using (5.3.11).
We have ` independent random variables corresponding to the positions
of the ` sprites. Moving a single sprite changes the number of set pixels by
at most m. So the probability that the total number of set pixels deviates
from its expectation by more than an ln n is bounded by
2
an ln n
!
a2 n2 ln n
2 exp = 2 exp 2
`m2 (n ln 2/m + o(1))m2
!
a2 ln n
= 2 exp
m ln 2 + o(m2 /n2 )
exp (a2 /m) ln n
2 /m
= na ,
where the inequality holds when n is sufficiently large.
Now choose a = cm
to get aprobability of deviating by more than n cm ln n of at most nc .
Since n cm ln n = o(1)n2 , this give us our desired bound.
a new job shows up, so that there are always n machines available to run
n jobs. Unfortunately, one of the ways the company cuts cost is by not
hiring programmers to replace the code from their previous randomized
load balancing mechanism, so when the i-th job arrives, it is still assigned
uniformly at random to one of the i available machines. This means that job
1 is always assigned to machine 1; job 2 is assigned with equal probability to
machine 1 or 2; job 3 is assigned with equal probability to machine 1, 2, or
3; and so on. These choices are all independent. The company claims that
the maximum load is still not too bad, and that the reduced programming
costs that they pass on to their customers make up for their poor quality
control and terrible service.
Justify the first part of this claim by showing that, with high probability,
the most loaded machine after n jobs has arrived has load O(log n).
Solution
Let Xij be the indicator variable for the event that machine i gets job j.
Then E [Xij ] = 1/j for all i j, and E [Xij ] = 0 when i > j.
Let Yi = nj=1 Xij be the load on machine i.
P
hP i
n Pn Pn
Then E [Yi ] = E j=1 Xij j=i 1/j
= j=1 1/j = Hn ln n + 1.
From (5.2.4), we have Pr [Yi R] 2 R as long as R > 2e E [Yi ]. So if
we let R = (c + 1) lg n, we get a probability of at most nc1 that we get
more than R jobs on machine i. Taking the union bound over all i gives
a probability of at most nc that any machine gets a load greater than
(c + 1) lg n. This works as long as (c + 1) lg n 2e(ln n + 1), which holds for
sufficiently large c. For smaller c, we can just choose a larger value c0 that
0
does work, and get that Pr [max Yi (c0 + 1) lg n] nc nc .
So for any fixed c, we get that with probability at least 1 nc the
maximum load is O(log n).
priorities is large enough that the probability that this produces a duplicate
is negligible, and that the choice of which node to re-roll is done obliviously,
without regard to the current priorities of nodes or the resulting shape of
the tree.
Changing the priority of x may break the heap property. To fix the
heap property, we either rotate x up (if its priority now exceeds its parents
priority) or down (if its priority is now less than that of one or both of its
children). In the latter case, we rotate up the child with the higher priority.
We repeat this process until the heap property is restored.
Compute the best constant upper bound you can on the expected number
of rotations resulting from executing a re-roll operation.
Solution
The best possible bound is at most 2 rotations on average in the worst case.
There is an easy but incorrect argument that 2 is an upper bound, which
says that if we rotate up, we do at most the same number of rotations as
when we insert a new element, and if we rotate down, we do at most the same
number of rotations as when we delete an existing element. This gives the
right answer, but for the wrong reasons: the cost of deleting x, conditioned
on the event that re-rolling its priority gives a lower priority, is likely to be
greater than 2, since the conditioning means that x is likely to be higher up
in the tree than average; the same thing happens in the other direction when
x moves up. Fortunately, it turns out that the fact that we dont necessarily
rotate x all the way to or from the bottom compensates for this issue.
This can be formalized using the following argument, for which I am
indebted to Adit Singha and Stanislaw Swidinski. Fix some element x, and
suppose its old and new priorities are p and p0 . If p < p0 , we rotate up,
and the sequence of rotations is exactly the same as we get if we remove
all elements of the original treap with priority p or less and then insert a
new element x with priority p0 . But now if we condition on the number k of
elements with priority greater than p, their priorities together with p0 are all
independent and identically distributed, since they are all obtained by taking
their original distribution and conditioning on being greater than p. So all
(k + 1)! orderings of these priorities are equally likely, and this means that
we have the same expected cost as an insertion into a treap with k elements,
which is at most 2. Averaging over all k shows that the expected cost of
rotating up is at most 2, and, since rotating down is just the reverse of this
process with a reversed distribution on priorities (since we get it by choosing
p0 as our old priority and p as the new one), the expected cost of rotating
APPENDIX A. ASSIGNMENTS 251
down is also at most 2. Finally, averaging the up and down cases gives that
the expected number of rotations without conditioning on anything is at
most 2.
We now give an exact analysis of the expected number of rotations, which
will show that 2 is in fact the best bound we can hope for.
The idea is to notice that whenever we do a rotation involving x, we
change the number of ancestors of x by exactly one. This will always be
a decrease in the number of ancestors if the priority of x went up, or an
increase if the priority of x went down, so the total number of rotations will
be equal to the change in the number of ancestors.
Letting Ai be the indicator for the event that i is an ancestor of x before
the re-roll, and A0i the indicator for the even that i is an ancestor of x after the
re-roll, then the number of rotations is just | i Ai i A0i |, which is equal
P P
to i |Ai A0i | since we know that all changes Ai A0i have the same sign. So
P
the expected number of rotations is just E [ i |Ai A0i |] = i E [|Ai A0i |],
P P
by linearity of expectation.
So we have to compute E [|Ai A0i |]. Using the same argument as in
6.3.2, we have that Ai = 1 if and only if i has the highest initial priority
of all elements in the range [min(i, x), max(i, x)], and the same holds for A0i
if we consider updated priorities. So we want to know the probability that
changing only the priority of x to a new random value changes whether i
has the highest priority.
Let k = max(i, x) min(i, x) + 1 be the number of elements in the
range under consideration. To avoid writing a lot of mins and maxes, lets
renumber these elements as 1 through k, with i = 1 and x = k (this may
involve flipping the sequence if i > x). Let X1 , . . . , Xk be the priorities of
these elements, and let Xk0 be the new priority of x. These k + 1 random
variables are independent and identically distributed, so conditioning on the
even that no two are equal, all (k + 1)! orderings of their values are equally
likely.
So now let us consider how many of these orderings result in |Ai A0i | = 1.
For Ai to be 1, X1 must exceed all of X2 , . . . , Xk . For A0i to be 0, X1 must
not exceed all of X2 , . . . , Xk1 , Xk0 . The intersection of these events is when
Xk0 > X1 > max(X2 , . . . , Xk ). Since X2 , . . . , Xk can be ordered in any of
(k 1)! ways, this gives
(k 1)! 1
Pr Ai = 1 A0i = 0 =
= .
(k + 1)! k(k + 1)
1. Suppose we insert a set S of n = |S| items into this hash table, using
a hash function h chosen at random from a strongly 2-universal hash
family H. Show that there is a constant c such that, for any t > 0, the
probability that at least n/2 + t items are lost is at most cn/t2 .
2. Suppose instead that we insert a set S of n = |S| items into this hash
table, using a hash function h chosen at random from a hash family
APPENDIX A. ASSIGNMENTS 253
Solution
1. Let Xi be the indicator variable for the event that the i-th element
of S is hashed to an odd-numbered bucket. Since H is strongly 2-
universal, E [Xi ] 1/2 (with equality when m is even), from which
it follows that Var [Xi ] = E [Xi ] (1 E [Xi ]) 1/4; and the Xi are
pairwise independent. Letting Y = ni=1 Xi be the total number of
P
items lost, we get E [Y ] n/2 and Var [Y ] n/4. But then we can
apply Chebyshevs inequality to show
Pr [Y n/2 + t] Pr [Y E [Y ] + t]
Var [Y ]
t2
n/4
2
t
1
= (n/t2 ).
4
So the desired bound holds with c = 1/4.
2. Show that the mixing time tmix for this process is polynomial in n.
APPENDIX A. ASSIGNMENTS 255
Solution
1. The stationary distribution is a uniform distribution on all nk place-
ments of the robots. To prove this, observe that two vectors increasing
vectors x and y are adjacent if and only if there is some i such that
xj = yj for all j 6= i and xj + d = yj for some d {1, +1}. In this
1
case, the transition probability pxy is 2n , since there is a n1 chance that
1
we choose i and a 2 chance that we choose d. But this is the same
as the probability that starting from y we choose i and d. So we
have pxy = pyx for all adjacent x and y, which means that a uniform
distribution satisfies x pxy = y pyx for all x and y.
To show that this stationary distribution is unique, we must show that
there is at least one path between any two states x and y. One way to
do this is to show that there is a path from any state x to the state
h1, . . . , ki, where at each step we move the lowest-index robot i that
is not already at position i. Since we can reverse this process to get
to y, this gives a path between any x and y that occurs with nonzero
probability.
2. This one could be done in a lot of ways. Below Ill give sketches of
three possible approaches, ordered by increasing difficulty. The first
reduces to card shuffling by adjacent swaps, the second uses an explicit
coupling, and the third uses conductance.
Of these approaches, I am personally only confident of the coupling
argument, since its the one I did before handing out the problem, and
indeed this is the only one I have written up in enough detail below to
be even remotely convincing. But the reduction to card shuffling is also
pretty straightforward and was used in several student solutions, so I
am convinced that it can be made to work as well. The conductance
idea I am not sure works at all, but it seems like it could be made to
work with enough effort.
(a) Lets start with the easy method. Suppose that instead of colliding
robots, we have a deck of n cards, of which k are specially marked.
Now run a shuffling algorithm that swaps adjacent cards at each
step. If we place a robot at the position of each marked card,
the trajectories of the robots follow the pretty much the same
distribution as in the colliding-robots process. This is trivially
the case when we swap a marked card with an unmarked card (a
robot moves), but it also works when we swap two marked cards
APPENDIX A. ASSIGNMENTS 256
(no robot moves, since the positions of the set of marked cards
stays the same; this corresponds to a robot being stuck).
Unfortunately we cant use exactly the same process we used in
9.3.3.3, because this (a) allows swapping the cards in the first
and last positions of the deck, and (b) doesnt include any moves
corresponding to a robot at position 1 or n trying to move off the
end of the line.
The first objection is easily dealt with, and indeed the cited result
of Wilson [Wil04] doesnt allow such swaps either. The second can
be dealt with by adding extra no-op moves to the card-shuffling
process that occur with probability 1/n, scaling the probabilities
of the other operations to keep the sum to 1. This doesnt affect
the card-shuffling convergence argument much, but it is probably
a good idea to check that everything still works.
Finally, even after fixing the card-shuffling argument, we still have
to argue that convergence in the card-shuffling process implies
convergence in the corresponding colliding-robot process. Here is
where the definition of total variation distance helps. Let C t be the
permutation of the cards after t steps, and let f : C t 7 X t map
permutations of cards to positions of robots. Let and 0 be the
stationary distributions of the card and robot processes, respec-
t 0
t
tively. Then d (f (C ), f ()) = max A Pr X A (A)
=
t T V1
1 t
maxA Pr C f (A) (f (A)) maxB Pr C B (B) =
dT V (C t , ). So convergence of C implies convergence of X = f (C).
(b) Alternatively, we can construct a coupling between two copies of
the process X t and Y t , where as usual we start X 0 in our initial
distribution (whatever it is) and Y 0 in the uniform stationary
distribution. At each step we generate a pair (i, d) uniformly at
random from {1, . . . , n} {1, +1}. Having generated this pair,
we move robot i in direction d in both processes if possible. It is
0 0
clear that once X t = Y t , it will continue to hold that X t = Y t
for all t0 > t.
To show convergence we must show that X t will in fact eventually
hit Y t . To do so, let us track Z t = kX t Y t k1 = ki=1 |Xit Yit |.
P
doesnt change Xjt for any j 6= i, the only change in Z t will occur
if one of Xit and Yit can move and the other cant. There are
several cases:
i. If i = k, d = +1, and exactly one of Xkt and Ykt is n, then the
copy of the robot not at n moves toward the copy at n, giving
Zt+1 Zt = 1. The same thing occurs if i = 1, d = 1, and
exactly one of X1t and Y1t is 1.
It is interesting to note that these two cases will account for
the entire nonzero part of E [Zt+1 Zt | Ft ], although we will
not use this fact.
ii. If i < k, d = +1, Xit + 1 = Xi+1 t , but Y t + 1 < X t , and
i i+1
Xi Yi , then robot i can move right in Y t but not in X t .
t t
and attempts to move to it. If the robot chooses not to move, it makes no
noise. If it chooses to move, but (i0 , j 0 ) is off the grid or occupied by one of
the m crates, then the robot stays at (i, j) and emits the noise. Otherwise it
moves to (i0 , j 0 ) and remains silent. The robots position at time 0 can be
any unoccupied location on the grid.
To keep the robot from getting walled in somewhere, whatever adversary
placed the crates was kind enough to ensure that if a crate was placed at
position (i, j), then all of the eight positions
(i 1, j + 1) (i, j + 1) (i + 1, j + 1)
(i 1, j) (i + 1, j)
(i 1, j 1) (i, j 1) (i + 1, j 1)
reachable by a kings move from (i, j) are unoccupied grid locations. This
means that they are not off the grid and not occupied by another crate, so
that the robot can move to any of these eight positions.
Your job is to devise an algorithm for estimating m to within relative
error with probability at least 1 , based on the noises emitted by the robot.
The input to your algorithm is the sequence of bits x1 , x2 , x3 , . . . , where xi
is 1 if the robot makes a noise on its i-th step. Your algorithm should run in
time polynomial in n, 1/, and log(1/).
Solution
It turns out that is a bit of a red herring: we can in fact compute the exact
number of crates with probability 1 in time polynomial in n and log(1/).
The placement restrictions and laziness make this an irreducible aperiodic
chain, so it has a unique stationary distribution . It is easy to argue from
reversibility that this is uniform, so each of the N = n2 m unoccupied
positions occurs with probability exactly 1/N .
It will be useful to observe that we can assign three unique unoccupied
positions to each crate, to the east, south, and southeast, and this implies
m n2 /4.
The idea now is to run the robot until the distribution on its position is
close to , and then see if it hits an obstacle on the next step. We can easily
count the number of possible transitions that hit an obstacle, since there are
4m incoming edges to the crates, plus 4n incoming edges to the walls. Since
1
each edge uv has probability u puv = 8N of being selected in the stationary
distribution, the probability q that we hit an obstacle starting from is
exactly n+m n+m
2N = n2 m . This function is not trivial to invert, but we dont
have to invert it: if we can compute its value (to some reasonable precision),
APPENDIX A. ASSIGNMENTS 260
1. We cross the edge as part of the left-to-right portion of the path (this
includes left-to-right moves that are part of detours). In this case we
have |j y| 1. This gives at most 3 choices for j, giving at most 3n3
possible paths. (The constants can be improved here.)
This gives at most 6n3 possible paths across each edge, giving a congestion
1
(6n3 )ij i0 j 0
ij pij,i0 j 0
1
= 1 (6n3 )N 2
N (1/8)
= 24n3 N 1
3
24n3 ( n2 )1
4
= 32n,
since we can argue from the placement restrictions that N n2 /4. This
immediately gives a bound 2 82 O(n2 ). using Lemma 9.4.3.
APPENDIX A. ASSIGNMENTS 261
So lets run for d512 ln ne = O(n2 ln n) steps for each sample. Starting
from any initial location, we will reach some distribution with dT V , =
O(n50 ). Let X be the number of obstacles (walls or crates) adjacent to the
current position, then we can apply Lemma 9.2.2 to get |E (X) E (X)|
4dT V (, ) = O(n50 ). The same bound (up to constants) also applies to
the probability = X/8 of hitting an obstacle, giving = 4(n + m)/(n2
m) O(n50 ). Note that is (n1 for all values of m.
Now take n10 ln(1/) samples, with a gap of d512 ln ne steps between
p
Figure A.2: Two hidden Space Invaders. On the left, the Space Invaders hide
behind random pixels. On the right, their positions are revealed by turning
the other pixels gray.
the bitmap wrap around as in Problem A.3.1.) Your algorithm should make
the probability of each bitmap that contains at least two copies of the sprite
be exactly equally likely, and should run in expected time polynomial in n
and m.
Solution
Rejection sampling doesnt work here because if the sprites are large, the
chances of getting two sprites out of a random bitmap are exponentially
small. Generating a random bitmap and slapping two sprites on top of it
also doesnt work, because it gives a non-uniform distribution: if the sprites
2
overlap in k places, there are 2n 2m+k choices for the remaining bits, which
means that we would have to adjust the probabilities to account for the effect
of the overlap. But even if we do this, we still have issues with bitmaps that
contain more than two sprites: a bitmap with three sprites can be generated
in three different ways, and it gets worse quickly as we generate more. It
may be possible to work around these issues, but a simpler approach is to
use the sampling mechanism from Karp-Luby [KL85] (see also 10.3).
2
Order all n2 positions u < v for the two planted sprites in lexicographic
order. For each pair of positions u < v, let Auv be the set of all bitmaps with
2
sprites at u and v. Then we can easily calculate |Auv | = 2n 2m+k where k
is the number of positions where sprites at u and v overlap, and so we can
sample a particular Auv with probability |Auv |/ st |Ast | and then choose an
P
APPENDIX A. ASSIGNMENTS 263
Solution
Let Yt = Xt + 12 min(t, ). We will show that {Yt } is a supermartingale.
Suppose we disinfect node v at time t, and that v has d0 d(v) uninfected
d0
neighbors. Then E [Xt+1 | Xt ] = Xt 1 + 2d(v) Xt 12 , because we always
APPENDIX A. ASSIGNMENTS 264
1. What is E [Y0 ]?
2. What is E [Y1 ]?
Solution
1. This is a straightforward application of linearity of expectation. Let Zit ,
for each i {1, . . . , n 1}, be the indicator for the event that Xit = 1
t
and Xi+1 = 0. For t = 0, Xi0 and Xi+1 0 are independent, so this event
h Pn1 i Pn1
occurs with probability 14 . So E [Y0 ] = E Zi0 = E Zi0 =
i=1 i=1
n1
(n 1) 14 = 4 .
2. Show that any correct algorithm for this problem will use more than n
coin-flips with probability at least 2O(n) .
Solution
1. Use rejection sampling: generate 3 bits, and if the resulting binary
number is not in the range 1, . . . , 6, try again. Each attempt consumes
3 bits and succeeds with probability 3/4, so we need to generate 43 3 = 4
bits on average.
It is possible to improve on this by reusing the last bit of a discarded
triple of bits as the first bit in the next triple. This requires a more
complicated argument to show uniformity, but requires only two bits
APPENDIX A. ASSIGNMENTS 266
2. Suppose that we have generated n bits so far. Since 6 does not evenly
divide 2n for any n, we cannot assign an output from 1, . . . , 6 to all
possible 2n sequences of bits without giving two outputs different
probabilities. So we must keep going in at least one case, giving a
probability of at least 2n = 2O(n) that we continue.
Appendix B
1. Your name.
(You will not be graded on the bureaucratic part, but you should do it
anyway.)
267
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 268
Solution
1. Suppose we have already inserted k elements. Then the next element
is equally likely to land in any of the positions A[1] through A[k + 1].
The number of displaced elements is then uniformly distributed in 0
through k, giving an expected cost for this insertion of k2 .
Summing over all insertions gives
n1
X k 1 n1
X
=
k=0
2 2 k=0
n(n 1)
= .
4
Its always nice when we get the same answer in situations like this.
2. Now we need to count how far the pointer moves between any two
consecutive elements. Suppose that we have already inserted k 1 > 0
elements, and let Xk be the cost of inserting the k-th element. Let
i and j be the indexes in the sorted list of the new and old pointer
positions after the k-th insertion. By symmetry, all pairs of distinct
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 270
This is such a simple result that we might reasonably expect that there
is a faster way to get it, and wed be right. A standard trick is to
observe that we can simulate choosing k points uniformly at random
from a line of n points by instead choosing k + 1 points uniformly at
random from a cycle of n + 1 points, and deleting the first point chosen
to turn the cycle back into a line. In the cycle, symmetry implies that
the expected distance between each point and its successor is the same
as for any other point; there are k + 1 such distances, and they add up
to n + 1, so each expected distance is exactly n+1
k+1 .
In our particular case, n (in the formula) is k and k (in the formula) is
2, so we get k+1
3 . Note we are sweeping the whole absolute value thing
under the carpet here, so maybe the more explicit derivation is safer.
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 271
However we arrive at E [Xk ] = k+13 (for k > 1), we can sum these
expectations to get our total expected cost:
" n # n
X X
E Xk = E [Xk ]
k=2 k=2
n
X k+1
=
k=2
3
1 n+1
X
= `
3 `=3
1 (n + 1)(n + 2)
= 3
3 2
(n + 1)(n + 2)
= 1.
6
Its probably worth checking a few small cases to see that this answer
actually makes sense.
For large n, this shows that the doubly-linked list wins, but not by much:
we get roughly n2 /6 instead of n2 /4. This is a small enough difference that
in practice it is probably dominated by other constant-factor differences that
we have neglected.
Solution
We can use linearity of expectation to compute the probability that any
particular edge is monochromatic, and then multiply by m to get the total.
Fix some edge uv. If either of u or v is recolored in step 2, then the
probability that c0u = c0v is exactly 1/k. If neither is recolored, the probability
that c0u = c0v is zero (otherwise cu = cv , forcing both to be recolored). So we
can calculate the probability that c0u = c0v by conditioning on the event A
that neither vertex is recolored.
This event occurs if both u and v have no neighbors with the same color.
The probability that cu = cv is 1/k. The probability that any particular
neighbor w of u has cw = cu is also 1/k; similarly for any neighbor w of
v. These events are all independent on the assumption that the graph is
triangle-free (which implies that no neighbor of u is also a neighbor of v).
So the probability that none of these 2r 1 events occur is (1 1/k)2r1 .
We then have
h i h i
Pr [cu = cv ] = Pr cu = cv A Pr A + Pr [cu = cv | A] Pr [A]
2r1 !
1 1
= 1 1 .
k k
Multiply by m to get
2r1 !
m 1
1 1 .
k k
For large k, this is approximately m (2r1)/k , which is a little
k 1e
bit better than than the m k expected monochrome edges from just running
step 1.
Repeated application of step 2 may give better results, particular if k is
large relative to r. We will see this technique applied to a more general class
of problems in 11.3.5.
3
Both endpoints have the same color.
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 273
Solution
Let Cij be the communication cost between machines i and j. This is just
an indicator variable for the event that i and j are assigned to different
1
machines, which occurs with probability 1 m
P
. We have C = 1i<jn Cij .
1. Expectation is a straightforward application of linearity of expectation.
There are n2 pairs of processes, and E [Cij ] = 1 m 1
for each pair, so
!
n 1
E [C] = 1 .
2 m
2. Variance is a little trickier because the Cij are not independent. But
they are pairwise independent: even if we fix the location of i and j,
1
the expectation of Cjk is still 1 m , so Cov [Cij , Cjk ] = E [Cij Cjk ]
E [Cij ] E [Cjk ] = 0. So we can compute
!
n 1 1
X
Var [C] = Var [Cij ] = 1 .
1i<j<n
2 m m
Solution
The expected cost of searching bucket i is E [dlg(Xi + 1)e]. This is the
expectation of a function of Xi , so we would like to bound it using Jensens
inequality (4.3).
Unfortunately the function f (n) = dlg(n + 1)e is not concave (because
of the ceiling), but 1 + lg(n + 1) > dlg(n + 1)e is. So the expected cost of
searching bucket i is bounded by 1 + lg(E [Xi ] + 1) = 1 + lg(k + 1).
Assuming we search the buckets in some fixed order until we find x, we
will search Y buckets where E [Y ] = n+12 . Because Y is determined by the
position of x, which is independent of the Xi , Y is also independent of the
Xi . So Walds equation (3.4.3) applies, and the total cost is bounded by
n+1
(1 + lg(k + 1)) .
2
0 0
1 1 5
2 5 2 3 6
3 4 6 4
Solution
For any node u, let depth(u) be the depth of u in T and depth0 (u) be the
depth of u in T 0 . Note that depth0 (u) is a random variable. We will start by
0
computing E depth (u) as a function of depth(u), by solving an appropriate
recurrence.
Let S(k) = depth0 (u) when depth(u) = k. The base cases are S(0) = 0
(the depth of the root never changes) and S(1) = 1 (same for the roots
children). For larger k, we have
1 1
E depth0 (u) = E 1 + depth0 (parent(u)) + E 1 + depth0 (parent(parent(u)))
2 2
or
1 1
S(k) = 1 + S(k 1) + S(k 2).
2 2
There are various ways to solve this recurrence. The most direct may be
to define a generating function F (z) = k
P
k=0 S(k)z . Then the recurrence
becomes
z 1 1
F = + zF + z 2 F.
1z 2 2
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 276
and similarly
2 /(depth(u)1)
Pr depth0 (u) E depth0 (u) t e2t
. (B.3.3)
q
1
Let t = 2 D ln (1/). Then the right-hand side of (B.3.2) and (B.3.3)
becomes e D ln(1/)/(depth(u)1) < e ln(1/) = . For = 12 nc1 , we get t =
q q
1
= c+1
c+1 )
2 D ln (2n 2 D(ln n + ln 2) = O D log n when c is constant.
0
For the lower bound on D , when can apply (B.3.3) to some u
single node
with depth (u) = D; this node by itself will give D0 23 DO D log n with
4
A less direct but still effective approach is to guess that S(k) grows linearly, and find a
and b such that S(k) ak + b. For this we need ak + b 1 + 12 (a(k 1)+ b)+ 12 (a(k 2) + b).
The bs cancel, leaving ak 1 + ak 32 a. Now the aks cancel, leaving us with 0 1 32 a
or a 2/3. We then go back and make b = 1/3 to get the right bound on S(1), giving the
bound S(k) 32 k + 13 . We can then repeat the argument for S(k) a0 k + b0 to get a full
bound 23 k S(k) 32 k + 13 .
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 277
probability at least 1 12 nc1 . For the upper bound, we need to take the max-
imum over all nodes. In general, an upper bound on the maximum of a bunch
of random variables is likely to be larger than an upper bound on any one of
the random variables individually, because there is a lot of room for one of
the variables to get unlucky, but we can happly the union bound to get around
i
this. For each individual u, we have Pr depth0 (u) 23 D + O D log n
1 c1
h
0 2D + O
i
u 12 nc1 = 12 nc . This com-
P
2 n , so Pr D 3 D log n
pletes the proof.
At each step, the part inspectors apply the following rules to decide which
test to apply:
For the first part, a fair coin-flip decides between the tests.
For subsequent parts, if the previous part passed, the inspectors become
suspicious and apply the rigorous test; if it failed, they relax and apply
the normal test.
For example, writing N+ for a part that passes the normal test, N- for
one that fails the normal test, R+ for a part that passes the rigorous test,
and R- for one that fails the rigorous test, a typical execution of the testing
procedure might look like N- N+ R- N- N+ R- N+ R- N- N- N- N+ R+ R-
N+ R+. This execution tests 16 parts and passes 7 of them.
Suppose that we test n parts. Let S be the number that pass.
1. Compute E [S].
2. Show that there a constant c > 0 such that, for any t > 0,
2 /n
Pr [|S E [S]| t] 2ect . (B.3.4)
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 278
Solution
Using McDiarmids inequality and some cleverness Let Xi be the
indicator variable for the event that part i passes, so that S = ni=1 Xi .
P
1. We can show by induction that E [Xi ] = 1/2 for all i. The base case
is X1 , where Pr [part 1 passes] = 12Pr [part
1 passes rigorous test] +
1
2 Pr [part 1 passes normal test] = 12 13 + 23 = 12 . For i > 1, E [Xi1 ] =
1/2 implies that part i is tested with the normal and rigorous tests
with equal probability, so the analysis for X1 carries through and gives
E [Xi ] = 1/2 as well. Summing over all Xi gives E [S] = n/2.
2. We cant use Chernoff, Hoeffding, or Azuma here, because the Xi are
not independent, and do not form a martingale difference sequence even
after centralizing them by subtracting off their expectations. So we
are left with McDiarmids inequality unless we want to do something
clever and new (we dont). Applying McDiarmid to the Xi directly
doesnt work so well, but we can make it work with a different set of
variables that generate the same outcomes.
Let Yi {A, B, C} be the grade of part i, where A means that it passes
both the rigorous and the normal test, B means that fails the rigorous
test but passes the normal test, and C means that it fails both tests.
In terms of the Xi , Yi = A means Xi = 1, Yi = C means Xi = 0,
and Yi = B means Xi = 1 Xi1 (when i > 1). We get the right
probabilities for passing each test by assigning equal probabilities.
We can either handle the coin-flip at the beginning by including an
extra variable Y0 , or we can combine the coin-flip with Y1 by assuming
that Y1 is either A or C with equal probability. The latter approach
improves our bound a little bit since then we only have n variables and
not n + 1.
6 i and ask what happens if Yi
Now suppose that we fix all Yj for j =
changes.
Solution
Let X be the random variable representing the final table size. Our goal is
to bound E [X].
First lets look at the probability that we get at least one collision between
consecutive elements when inserting n elements into a table with m locations.
Because the pairs of consecutive elements overlap, computing the exact
probability that we get a collision is complicated, but we only need an upper
bound.
We have n 1 consecutive pairs, and each produces a collision with
probability at most 1/m. This gives a total probability of a collision of at
most (n 1)/m.
Let k = dlg ne, so that 2k n. Then the probability of a consecutive
collision in a table with 2k+` locations is at most (n1)/2k+` < 2k /2k+` = 2` .
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 280
Since the events that collisions occur at each table size are independent, we
can compute, for ` > 0,
h i h i
Pr X = 2k+` Pr X 2k+`
`1
2i
Y
i=0
`(`1)/2
=2 .
since the series converges to some constant that does not depend on k. But
we chose k so that 2k = O(n), so this gives us our desired bound.
Solution
Insert the sequence 1 . . . n.
Let us first argue by induction on i that all elements x with h(x) = m
appear as the uppermost elements of the right spine of the treap. Suppose
that this holds for i 1. If h(i) = m, then after insertion i is rotated up
until it has a parent that also has heap key m; this extends the sequence
of elements with heap key m in the spine by 1. Alternatively, if h(i) < m,
then i is never rotated above an element x with h(x) = m, so the sequence
of elements with heap key m is unaffected.
Because each new element has a larger tree key than all previous elements,
inserting a new element i requires moving past any elements in the right
spine, and in particular requires moving past any elements j < i with
h(j) = m. So the expected cost of inserting i is at least the expected
number of such elements j. Because h is chosen from a strongly 2-universal
hash family, Pr [h(j) = m] = 1/m for any j, and by linearity of expectation,
E [|{j < i | h(j) = m}|] = (i 1)/m. Summing this quantity over all i gives
a total expected insertion cost of at least n(n 1)/2m = (n2 /m).
Solution
This is a job for the optional stopping theorem. Essentially we are going to
follow the same analysis from 8.5.1 for a random walk with two absorbing
barriers, applied to Xt .
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 282
1. For the first part, we show that (Xt , Ft ) is a martingale. The intuition
is that however the bits in At are arranged, there are always exactly
the same number of positions where a zero can be replaced by a one as
there are where a one can be replaced by a zero.
Let Rt be the random location chosen in state At . Observe that
But then
n1
X 1
E [Xt+1 | Ft ] = (Xt + A[i] A[(i + 1) mod n])
i=0
n
1 1
= Xt + Xt Xt
n n
= Xt ,
E [X ] = E [X0 ] = k.
But then
E [X ] = n Pr [X = n] + 0 Pr [X = 0] = k,
so E [X ] = k/n.
k 2 kn 2 E [ ] /n
which gives
kn k 2
E [ ]
2/n
kn2 k 2 n
= .
2
This is maximized at k = bn/2c, giving
bn/2c n2 (bn/2c)2 n
E [ ] .
2
To show that this bound applies in the worst case, observe that if we
start with have contiguous regions of k ones and n k zeros in At , then
(a) Yt = 1, and (b) the two-region property is preserved in At+1 . In
this case, for t < it holds that E [Zt+1 | Ft ] = Zt + 2Yt /n 2/n = Zt ,
2 2n
so Zt is a martingale, and thus E [ ] = kn k 2 . This shows that the
initial state with bn/2c consecutive zeros and dn/2e consecutive ones
(or vice versa) gives the claimed worst-case time.
Solution
Consider the n diagonal elements in positions Aii . For each such element,
there is a 1/n chance at each step that its row or column is chosen. The
6
Ive been getting some questions about what this means, so here is an attempt to
translate it into English.
Recall that f (n) is (g(n)) if limn fg(n)
(n)
goes to infinity, and f (n) is o(g(n)) if
limn fg(n)
(n)
goes to zero.
The problem is asking you to show that there is some f (n) that is more than a constant
times n, such that the total variation distance between Af (n) becomes arbitrarily close to
1 for sufficiently large n.
So for example, if you showed that at t = n4 , dT V (At , B) 1 log12 n , that would
2 n
demonstrate the claim, because limn nn goes to infinity and limn 1/ log
1
= 0. These
functions are, of course, for illustration only. The actual process might or might not
converge by time n4 .)
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 285
time until every diagonal node is picked at least once maps to the coupon
collector problem, which means that it is (n log n) with high probability
using standard concentration bounds.
Let C be the event that there is at least one diagonal element that is
in its original position. If there is some diagonal node that has not moved,
C holds; so with probability 1 o(1), At holds at some time t that is
(n log n) = (n). But by the union bound, C holds in B with probability
at most n n2 = 1/n. So the difference between the probability of C in At
and B is at least 1 o(1) 1/n = 1 o(1).
Solution
Since its a Las Vegas algorithm, Markov chain Monte Carlo is not going to
help us here. So we can set aside couplings and conductance and just go
straight for generating a solution.
First, lets show that we can generate uniform colorings of an n-node
line in linear time. Let Xi be the color of node i, where 0 i < n. Choose
X0 uniformly at random from all three colors; then for each i > 0, choose
Xi uniformly at random from the two colors not chosen for Xi1 . Given a
coloring, we can show by induction on i that it can be generated by this
process, and because each choice is uniform and each coloring is generated
only once, we get all 3 2n1 colorings of the line with equal probability.
Now we try hooking Xn1 to X0 . If Xn1 = X0 , then we dont have a
cycle coloring, and have to start over. The probability that this event occurs
is at most 1/2, because for every path coloring with Xn1 = X0 , there is
another coloring where we replace Xn1 with a color not equal to Xn2 or
X0 . So after at most 2 attempts on average we get a good cycle coloring.
This gives a total expected cost of O(n).
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 286
too low at any time t, all your worldly goods will be repossessed, and you
will have nothing but your talent for randomized algorithms to fall back on.
Note: an earlier version of this problem demanded a tighter
bound.
Show that when n and m are sufficiently large,
it is always possible to
choose a subset S of size n/2 so that wt m n ln nm for all 0 < t m,
and give an algorithm that finds such a subset in time polynomial in n and
m on average.
Solution
Suppose that we flip a coin independently to choose whether to include each
investment i. There are two bad things that can happen:
1. We lose too much at some time t from the investments the coin chooses.
If we can show that the sum of the probabilities of these bad events is
less than 1, we get the existence proof we need. If we can show that it is
enough less than 1, we also get an algorithm, because we can test in time
O(nm) if a particular choice works.
Let Xi be the indicator variable for the event that we include investment
i. Then
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 287
n
X t
X
wt = Xi aij
i=1 j=1
n t
1 1
X X
= + Xi aij
i=1
2 2 j=1
t X n n t
!
1X 1
X X
= aij + Xi aij
2 j=1 i=1 i=1
2 i=1
n t
!
1
X X
= Xi aij .
i=1
2 i=1
h i
Because Xi 12 is always 12 , E Xi 12 = 0, and each aij is 1, each
term
in the
P outermost
sum is a zero-mean random variable that satisfies
t t m
Xi 12 a 2 2 . So Hoeffdings inequality says
j=1 ij
h i 2 2
Pr wt E [wt ] < m n ln nm em n ln nm/(2n(m/2) )
= e2 ln nm
= (nm)2 .
Summing over all t, the probability that this bound is violated for any t
is at most n21m .
For the second source of error, we have Pr [ ni=1 Xi 6= n/2] = 1 n2 /2n =
P
1 (1/ n). So the total probability that the random assignment fails is
bounded by 1 (1/ n) + 1/n, giving a probability that it succeeds of at
least (1/ n) 1/(n2 m) = ( n). It follows that generating and testing
random assignments gives an assignment with the desired characteristics
after ( n) trials on average, giving a total expected cost of (n3/2 m).
Solution
Suppose we condition on a particular set of k elements appearing in positions
A[1] through A[k]. By symmetry, all k! permutations of these elements are
equally likely. Putting the largest two elements in A[k 1] and A[k] leaves
(k 2)! choices for the remaining elements, giving a probability of a double
record at k of exactly (k2)!
k!
1
= k(k1) .
Applying linearity of expectation gives a total expected number of double
records of
n n
X 1 X 1
k=2
k(k 1) k=2 (k 1)2
X 1
k=2
(k 1)2
X 1
=
k=1
k2
2
=
6
= O(1).
Since the expected number of double records is at least 1/2 = (1) for
n 2, this gives a tight asymptotic bound of (1).
I liked seeing our old friend 2 /6 so much that I didnt notice an easier
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 289
Solution
This problem produced the widest range of solutions, including several very
clever deterministic algorithms. Here are some examples.
time we get a labeling in which the number of happy nodes is at least the
n/2 expected happy nodes we started with.
With a bit of care, the cost can be reduced to linear: because each new
labeled node only affects its own probability of happiness and those of its
three neighbors, we can update the conditional expectation by just updating
the values for those four nodes. This gives O(1) cost per step or O(n) total.
Solution
We need two ideas here. First, well show that Xt t2 is a martingale, despite
the fact that Xt by itself isnt. Second, well use the idea of stopping Xt
when it hits s + 1, creating a new martingale Yt = Xt 2 (t ) where is
the first time where Xt = s (and t is shorthand for min(t, )). We can
then apply Markovs inequality to Xn .
To save time, well skip directly to showing that Yt is a martingale. There
are two cases:
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 291
1. If t < , then
1 1
E [Yt+1 | Yt , t < ] = (Xt + 1)2 (t + 1) + (Xt 1)2 (t + 1)
2 2
2
= Xt + 1 (t + 1)
= Xt2 t
= Yt .
The engineer reasons that since a typical monitor covers 5 grid locations,
using n2 /4 monitors on average should cover (5/4)n2 locations, with the
extra monitors adding a little bit of safety to deal with bad random choices.
So few if any processing units should escape.
1. Compute the exact expected number of processing units that are not
within range of any monitor, as a function of n. You may assume
n > 0.
Solution
1. This part is actually more annoying, because we have to deal with
nodes on the edges. There are three classes of nodes:
2. Let Xij be the indicator for a monitor at position (i, j). Recall that
we have assumed that these variables are independent.
APPENDIX B. SAMPLE ASSIGNMENTS FROM SPRING 2014 293
1. Your name.
(You will not be graded on the bureaucratic part, but you should do it
anyway.)
294
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 295
Solution
If we can figure out the probability that bins i and i + 1 are both empty for
some particular i, then by symmetry and linearity of expectation we can just
multiply by n 1 to get the full answer.
For bins i and i + 1 to be empty, every ball must choose another bin.
This occurs with probability (1 2/n)m . The full answer is thus n(1 2/n)m ,
or approximately ne2m/n when n is large.
Solution
Well use the law of total probability. First observe that the probability that
a random labeling yields a zero sum for any single vertex and its neighbors is
exactly 1/(n + 1); the easiest way to see this is that after conditioning on the
values of the neighbors, there is only one value in n + 1 that can be assigned
to the vertex itself to cause a failure. Now sum this probability over all n
vertices to get a probability of failure of at most n/(n + 1). It follows that
after n + 1 attempts on average (each of which takes O(n2 ) time to check all
the neighborhood sums), the algorithm will find a good labeling, giving a
total expected time of O(n3 ).
E [T | T n] = 2n + 1. (C.1.1)
Solution
Expand (C.1.1) using the definition of conditional expectation to get
X
2n + 1 = x Pr [T = x | T n]
x=0
X Pr [T = x T n]
= x
x=0
Pr [T n]
1 X
= x Pr [T = x] ,
Pr [T n] x=n
which we can rearrange to get
X
x Pr [T = x] = (2n + 1) Pr [T n] , (C.1.2)
x=n
n Pr [T = n] = (2n + 1) Pr [T = n] 2 Pr [T n + 1]
= (2n + 3) Pr [T = n] 2 Pr [T = n] 2 Pr [T n + 1]
= (2n + 3) Pr [T = n] 2 Pr [T n] .
A little bit of algebra turns this into
Pr [T = n] 2
Pr [T = n | T n] = = .
Pr [T n] n+3
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 297
that choose the left machine and the number that choose the right. By
symmetry, the expectation of S is zero. What is the variance of S as a
function of p and n?
Solution
P
To compute the variance, well use (5.1.4), which says that Var [ i Xi ] =
P P
i Var [Xi ] + 2 i<j Cov [Xi , Xj ].
Recall that Cov [Xi , Xj ] = E [Xi Xj ] E [Xi ] E [Xj ]. Since the last term
is 0 (symmetry again), we just need to figure out E [Xi Xj ] for all i j (the
i = j case gets us Var [Xi ]).
First, lets compute E [Xj = 1 | Xi = 1]. Its easiest to do this starting
with the j = i case: E [Xi | Xi = 1] = 1. For larger j, compute
It follows that
We next have
as calculated in (C.2.1).
So now we just need to evaluate the horrible sum.
X X X n
n X
Var [Xi ] + 2 Cov [Xi , Xj ] = n + 2 (2p 1)ji
i i<j i=1 j=i+1
n ni
X X
=n+2 (2p 1)k
i=1 k=1
n
X (2p 1) (2p 1)ni+1
=n+2
i=1
1 (2p 1)
n
n(2p 1) 1 X
=n+ (2p 1)m
1p 1 p m=1
n(2p 1) (2p 1) (2p 1)n+1
=n+ .
1p 2(1 p)2
(C.2.2)
This covers all but the p = 1 case, for which the geometric series formula
fails. Here we can compute directly that Var [S] = n2 , since S will be n
with equal probability.
For smaller values of p, plotting (C.2.2) shows the variance increasing
smoothly starting at 0 (for even n) or 1 (for odd n) at p = 0 to n2 in the limit
as p goes to 1, with an interesting intermediate case of n at p = 1/2, where
all terms but the first vanish. This makes a certain intuitive sense: when
p = 0, the processes alternative which machine they take, which gives an
even split for even n and a discrepancy of 1 for odd n; when p = 1/2, the
processes choose machines independently, giving variance n; and for p = 1,
the processes all choose the same machine, giving n2 .
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 299
2. Let c > 0. Show that the absolute value of the difference between the
actual
number of scan operations and the expected number is at most
O( cn log n) with probability at least 1 nc .
Solution
1. Number the balls 1 to n. Forball
i,there are i1 bins already occupied,
giving a probability of i1
n
i2
n1 that we choose an occupied bin on
both attempts and incur a scan. Summing over all i gives us that the
expected number of scans is:
n n1
i1 i2 1
X X
= (i2 i)
i=1
n n1 n(n 1) i=1
1 (n 1)n(2n 1) (n 1)n)
=
n(n 1) 6 2
(2n 1) 1
=
6 2
n2
,
3
provided n 2. For n < 2, we incur no scans.
2. Its tempting to go after this using Chernoffs inequality, but in this case
Hoeffding gives a better bound. Let S be the number of scans. Then S is
the sum of n independent Bernoulli random variables,
so 5.3.3says that
2
Pr [|S E [S]| t] 2e2t /n . Now let t = cn ln n = O( cn log n)
to make the right-hand side 2n2c nc for sufficiently large n.
Solution
Let S be the total vote. The intuition here is that if there is no conspiracy,
S is concentrated around 0, and if there is a conspiracy, S is concentrated
around m. So if m is sufficiently large and |S| m/2, we can reasonably
guess that there is a conspiracy.
We need to prove two bounds: first, that the probability that we see
|S| m/2 when there is no conspiracy is small, and second, that the
probability that we see |S| < m/2 when there is a conspiracy is large.
For the first case, let Xi be the total vote cast by the i-th group. This
will be ni with equal probability, where ni k is the size of the group.
P
This gives E [Xi ] = 0. We also have that ni = n.
Because the Xi are all bounded, we can use Hoeffdings inequality (5.3.1),
so long as we can compute an upper bound on n2i . Here we use the fact
P
P 2
that ni is maximized subject to 0 ni k and ni = 0 by setting as
P
ln 2 m2 /8nk c ln n,
For the second case, repeat the above analysis on the n m votes except
the m from the conspiracy. Again we get that if m = ( ckn log n), the
c
that these votes exceed m/2 is bounded by n . So in both cases
probability
m = ( ckn log n) is enough.
To ensure that Bi+2 makes sense even for i = n, assume that there exist
random variables Xn+1 and Xn+2 and the corresponding Bn+1 and Bn+2 .
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 302
Solution
This is a job for McDiarmids inequality (5.3.11). Observe that S is a function
of X1 . . . Xn+2 . We need to show that changing any one of the Xi wont
change this function by too much.
From the description of the Yi , we have that Xi can affect any of Yi2 (if
Xi2 = X), Yi1 (if Xi1 = /) and Yi . We can get a crude bound by observing
P
that each Yi ranges from 0 to 30, so changing Xi can change Yi by at most
90, giving ci 90. A better bound can be obtained by observing that Xi
contributes only Bi to each of Yi2 and Yi1 , so changing Xi can only change
these values by up to 10; this gives ci 50. An even more pedantic bound
can be obtained by observing that X1 , X2 , Xn+1 , and Xn+2 are all special
cases, with c1 = 30, c2 = 40, cn+1 = 20, and cn+2 = 10, respectively; these
values can be obtained by detailed meditation on the rules above.
We thus have n+2 2 2 2 2 2 2
i=1 ci = (n 2)50 + 30 + 40 + 20 + 10 = 2500(n
P
Solution
An easy way to do this is to produce a tree that consists of a single path,
which we can do by arranging that the remaining keys have priorities that
are ordered the same as their key values.
Heres a simple strategy that works. Divide the keys into n ranges of
n keys each (1 . . . n, n + 1 . . . 2 n, etc.).3 Rank the priorities from 1
to n. From each range (i 1) n . . . i n, choose a key to keep whose priority
is also ranked in the range (i 1) n . . . i n (if there is one), or choose no
key (if there isnt). Delete all the other keys.
For a particular range, we are drawing n samples without replacement
from the n priorities, and there are n possible choices that cause us
tokeep a key in that range. The probability that every draw misses is
Q n n
i=1 (1 n/(n i + 1)) (1 1/ n) e1 . So each range contributes
1
at least 1 e keys on average. Summing over all n ranges gives a
sequence of keys with increasing priorities with expected length at least
(1 e1 ) n = ( n).
An alternative solution is to apply the Erds-Szekeres theorem [ES35],
which says that every sequence of length k 2 + 1 has either an increasing
subsequence of length k + 1 or a decreasing sequence of k + 1. Consider the
sequence of priorities corresponding to the keys 1 . . . n; letting k = b n 1c
gives a subsequence of length at least n 1 that is either increasing or
decreasing. If we delete all other elements of the treap, the elements cor-
responding to this subsequence will form a path, giving the desired bound.
Note that this does not require any probabilistic reasoning at all.
Though not required for the problem, its possible to show that ( n)
is the best possible bound here. The idea is that the number of possible
sequences of keys that correspond to a path of length k in a binary search
tree is exactly nk 2k1 ; the nk corresponds to choosing the keys in the path,
and the 2k1 is because for each node except the last, it must contain either
the smallest or the largest of the remaining keys because of the binary search
tree property.
Since each such sequence will be a treap path only if the priorities are
decreasing (with probability 1/k!), the union bound says that the probability
3
To make our life easer, well assume that n is a square. This doesnt affect the
asymptotic result.
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 304
*
/ \
a / \ b
/ \
* *
/ \ \
a / \ b \ b
/ \ \
aa ab bb
Figure C.1: A radix tree, storing the strings aa, ab, and ba.
n k1
of having any length-k paths is at most k 2 /k!. But
!
n k1 (2n)k
2 /k!
k 2(k!)2
(2n)k
2(k/e)2k
1
= (2e2 n/k 2 )k .
2
This is exponentially small for k 2e2 n, showing that with high probability
all possible paths have length O( n).
Solution
We need to create a new node for each prefix of the new string that is not
already represented in the tree.
For a prefix of length `, the chance that none of the n strings have this
n
prefix is exactly 1 m` . Summing over all ` gives that the expected
n
number of new nodes is k`=0 1 m` .
P
4
If you actually need to do this, there exist better data structures for this problem. See
[KNW10].
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 306
Solution
Well apply the usual error budget approach and show that the probability
\
that n d is too big and the probability that n \ d is too small are both
small. For the moment, we will leave c and as variables, and find values
that work at the end.
Lets start with the too-big side. To get A[k] = 1, we need h(xi ) = k for
some xi that is inserted but not subsequently deleted. There are nd such xi ,
and each gives h(xi ) = k with probability 2k . So Pr [A[k] = 1] (n d)2k .
This gives
h i h i
\
Pr n d (n d)c = Pr kb dlg ((n d)c)e
(n d)2k
X
k=dlg((nd)c)e
= 2(n d)2dlg((nd)c)e
2
.
c
nd d
1 2k ; the probability of the second is 1 1 2k . So we have
nd d
Pr [A[k] = 0] 1 2k + 1 1 2k
exp 2k (n d) + 1 exp 2k + 22k d
exp 2dlg((nd)/c))e (n d) + 1 exp 2 2dlg((nd)/c))e d
exp 2 lg((nd)/c)) (n d) + 1 exp 2 2 lg((nd)/c))+1 d
4cd
c
= e + 1 exp
nd
4cd
ec +
nd
c 4c
e + .
1
So our total probability of error is bounded by 2c + ec + 1
4c
. Let c = 8
1 8 128 1
and = 1/128 to make this less than 4 + e + 127 16 0.313328 < 1/3,
giving the desired bound.
1 procedure insert(x)
2 for i 0 to do
3 for j 1 to k do
4 if Ti [hij (x)] = then
5 Ti [hij (x)] x
6 return
Solution
The idea is that we use Ti+1 only if we get a collision in Ti . Let Xi be the
indicator for the event that there is a collision in Ti . Then
X
E [steps] 1 + E [Xi ] (C.4.1)
i=0
and
X
E [space] m0 + E [Xi ] mi+1 . (C.4.2)
i=0
Let ` be the largest value such that m` n2+ . We will show that, for
an appropriate choice of k, we are sufficiently unlikely to get a collision in
round ` that the right-hand sides of (C.4.2) and (C.4.2) end up being not
much more than the corresponding sums up to ` 1.
From our choice of `, it follows that (a) ` lg lg n2+ = lg lg n+lg(2+) =
O(log log n); and (b) m`+1 > n2+ , giving m` = m`+1 > n1+/2 . From this
we get E [X` ] n(n/m` )k < n1k/2 .
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 309
For E [steps], compute the same sum without all the mi+1 factors. This
makes the tail terms even smaller, so they is still bounded by a constant,
and the head becomes just `i=0 1 = O(log log n).
P
2. Use this to compute the exact probability that hi (x) 6= hi (y) when
m = 0, m = n/2, and m = n.
Hint: You may find it helpful to use the identity (a mod 2) = 12 (1(1)a ).
Solution
1. Observe that hi (x) 6= hi (y) if an only if i chooses an odd number of
indices where x and y differ. Let p = m/n be the probability that each
index in i hits a position where x and y differ, and let q = 1 p. Then
the event that we get an odd number of differences is
k k
! !
X k j kj X 1 k
(j mod 2) p q = 1 (1)j pj q kj
j=0
j j=0
2 j
k k
! !
1X k j kj 1 X k
= p q (p)j q kj
2 j=0 j 2 j=0 j
1 1
= (p + q)k (p + q)k
2 2
1 (1 2(m/n))k
= .
2
11k
2. For m = 0, this is 2 = 0.
k
For m = n/2, its 102 = 1
2 (assuming k > 0).
k
For m = n, its 1(1)
2 = (k mod 2).
In fact, the chances of not colliding as a function of m are symmetric
around m = n/2 if k is even and increasing if k is odd. So we can only hope
to use this as locality-sensitive hash function in the odd case.
Solution
The trick is to observe that Xt2 + Yt2 + Zt2 t is a martingale, essentially
following the same analysis as for Xt2 t for a one-dimensional random walk.
Suppose we pick Xt to change. Then
h
2
i 1
E Xt+1 Xt = (Xt + 1)2 + (Xt 1)2
2
= Xt2 + 1.
So
h i
2 2 2
E Xt+1 + Yt+1 + Zt+1 (t + 1) Xt , Yt , Zt , X changes = Xt2 + Yt2 + Zt2 t.
immediately gives E [ ] k 2 .
To get an upper bound, observe that X21 + Y21 + Z21 < k 2 , and
that exactly one of these three term increases between 1 and . Suppose
its X (the other cases are symmetric). Increasing X by 1 sets X2 =
X21 + 2X 1 + 1. So we get
X2 + Y2 + Z2 = X21 + Y21 + Z21 + 2X 1 + 1
< k 2 + 2k + 1.
So we have k 2 E [ ] < k 2 + 2k + 1, giving E [ ] = (k 2 ). (Or k 2 + O(k)
if we are feeling really precise.)
Solution
As usual, let Xt be a copy of the chain starting in an arbitrary initial state
and Yt be a copy starting in the stationary distribution.
From the Metropolis-Hastings algorithm, the probability that the walk
moves to a particular child is 1/3, so the probability that the depth increases
after one step is at most 2/3. The probability that the walk moves to the
parent (if we are not already at the root) is 1/3.
Well use the same choice (left, right, or parent) in both the X and
Y processes, but it may be that only one of the particles moves (because
the target node doesnt exist). To show convergence, well track Zt =
max(depth(Xt ), depth(Yt )). When Zt = 0, both Xt and Yt are the root
node.
There are two ways that Zt can change:
1. Both processes choose parent; if Zt is not already 0, Zt+1 = Zt 1.
This case occurs with probability 1/3.
Solution
Well use rejection sampling. The idea is to choose a node in the infinite
binary tree with probability proportional to d , and then repeat the process
if we picked a node that doesnt actually exist. Conditioned on finding a
depth(x)
node i that exists, its probability will be P depth(j) .
j
If we think of a node in the infinite tree as indexed by a binary strength
of length equal to its depth, we can generate it by first choosing the length
X and then choosing the bits in the string. We want Pr [X = n] to be
proportional to 2n n = (2/)n . Summing the geometric series gives
(2/)n
Pr [X = n] = .
1 (2/)
Solution
This can be solved using a fairly straightforward application of Karp-
Luby [KL85] (see 10.3). Recall that for Karp-Luby we need to be able to
express our target set U as the union of a polynomial number of covering sets
Uj , where we can both compute the size of each Uj and Psample uniformly from
it. We can then estimate |U | = j,xUj f (j, x) = j |Uj | Pr [f (j, x) = 1]
P
where f (j, x) is the indicator for the event that x 6 Uj 0 for any j 0 < j
and in the probability, the pair (j, x) is chosen uniformly at random from
{(j, x) | x Uj }.
In this case, let Uj be the set of all permutations that are increasing on
Sj . We can specify each such permutation by specifying the choice of which
kj = |Sj | elements are in positions i1 . . . ikj (the order of these elements
is determined by the requirement that the permutation be increasing on
Sj ) and specifying the order of the remaining n kj elements. This gives
n
kj (n kj )! = (n)nkj such permutations. Begin by computing these counts
for all Sj , as well as their sum.
We now wish to sample uniformly from pairs (j, ) where each is an
element of Sj . First sample each j with probability |Sj |/ ` |S` |, using the
P
bacab bacab
ccaac ccaac
bbbac babac
bbaaa bbaaa
acbab acbab
Figure C.2: Non-futile (left) and futile (right) word search grids for the
lexicon {aabc, ccca}
word search puzzles with no solution for a given lexicon. That is, given a set
of words S over some alphabet and a grid size n, the output should be an
n n grid of letters such that no word in S appears as a contiguous sequence
of letters in one of the eight directions anywhere in the grid. We will refer to
such puzzles as futile word search puzzles.
Solution
1. Well apply the symmetric version of the Lovsz local lemma. Suppose
the grid is filled in independently and uniformly at random with
characters from . Given a position ij in the grid, let Aij be the
event that there exists a word in S whose first character is at position
ij; observe that Pr [Aij ] 8pS by the union bound (this may be an
overestimate, both because we might run off the grid in some directions
and because the choice of initial character is not independent). Observe
also that Aij is independent of any event Ai0 j 0 where |i i0 | 2k 1 or
|j j 0 | 2k 1, because no two words starting at these positions can
overlap. So we can build a dependency graph with p 8pS and d
(4k3)2 . The Lovsz local lemma shows that there exists an assignment
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 316
where no Aij occurs provided ep(d + 1) < 1 or 8epS ((4k 3)2 + 1) < 1.
1
This easily holds if pS < 8e(4k 1 2 .
2 ) = 128e k
2. For this part, we can just use Moser-Tardos [MT10], particularly the
symmetric version described in Corollary 11.3.4. We have a collection
of m = O(n2 ) bad events, with d = (k 2 ), so the expected number of
resamplings is bounded by m/d = O(n2 /k 2 ). Each resampling requires
checking every position in the new grid for an occurrence of some string
in S; this takes O(n2 k |S|) time per resampling even if we are not
very clever about it. So the total expected cost is O(n4 |S|/k).
With some more intelligence, this can be improved. We dont need to
recheck any position at distance greater than k from any of the at most
k letters we resample, and if we are sensible, we can store S using a
radix tree or some similar data structure that allows us to look up all
words that appear as a prefix of a given length-k string in time O(k).
This reduces the cost of each resampling to O(k 3 ), with an additive
cost of O(k |S|) to initialize the data structure. So the total expected
cost is now O(n2 k + |S|).
Solution
Assign each player randomly to a faction. Let Xij be the number of players
in Si that are assigned to faction j. Then E [Xij ] = |Si |/3. Applying the
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 317
1
Pr [Xij |Si |/2] = Pr Xij 1 + E [Xij ]
2
2 !
1
exp (|Si |/3) /3
2
= e|Si |/36 .
Solution
Suppose we are have state St at time t. We will use a random walk where
we choose a vertex uniformly at random to add to or remove from St , and
carry out the action only if the resulting set is still a dominating set.
In more detail: For each vertex v, with probability 1/n, St+1 = St {v}
if v 6 St , St+1 = St \ {v} if v St and St \ {v} is a dominating set, and
St+1 = St otherwise. To implement this transition rule, we need to be able
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 318
to choose a vertex v uniformly at random (easy) and test in the case where
v St if St \ {v} is a dominating set (also polynomial: for each vertex, check
if it or one of its neighbors is in St \ {v}, which takes time O(|V | + |E|)).
Note that we do not need to check if St {v} is a dominating set.
For any pair of adjacent states S and S 0 = S \ {v} the probability of
moving from S to S 0 and the probability of moving from S 0 to S are both 1/n.
So the Markov chain is reversible with a uniform stationary distribution.
This is an aperiodic chain, because there exist minimal dominating sets
for which there is a nonzero chance that St+1 = St .
It is irreducible, because for any dominating set S, there is a path to
the complete set of vertices V by adding each vertex in V \ S one at a time.
Conversely, removing these vertices from V gives a path to S. This gives a
path S V T between any two dominating sets S and T .
r
g r
b
Solution
Though it is possible, and tempting, to go after this using Karp-Luby (see
10.3), naive sampling is enough.
If a graph has at least one triangle (which can be checked in O(n3 )
time just by enumerating all possible triangles), then the probability that
that particular triangle is tricolored when colors are chosen uniformly and
independently at random is 6/27 = 2/9. This gives a constant hit rate , so
by Lemma 10.2.1, we can get relative error with 1 probability using
APPENDIX C. SAMPLE ASSIGNMENTS FROM SPRING 2013 319
1
O 2
log 1 samples. Each sample costs O(n3 ) time to evaluate (again, brute-
force checking of all possible triangles), for a total cost of O n3 2 log 1 .
2. Mark any square whose label is larger than any other label in its row
and column.
Solution
Each square is marked if it is the largest of the 2n 1 total squares in its
row and column. By symmetry, each of these 2n 1 squares is equally likely
to be the largest, so the probability that a particular square is marked is
1
exactly 2n1 . By linearity of expectation, the total expected number of
n2
marked squares is then 2n1 .
Solution
The basic idea is to just go through positions 0, 1, 2, . . . until we encounter
the target, but we have to be a little careful about parity to make sure we
dont pass it by accident.8
Let Xi = 1 be the increment of the targets i-th move, and let Si =
Pi
j=1 Xj , so that its position after i steps is n + Si mod 2n.
Let Yi be the position of the pursuer after i steps.
First move: stay at 0 if n is odd, move to 1 if n is even. The purpose of
this is to establish the invariant that n + Si Yi is even starting at i = 1.
For subsequent moves, let Yi+1 = Yi + 1. Observe that this maintains the
invariant.
We assume that n is at least 2. This is necessary to ensure that at time
1, Y1 n + S1 .
Claim: if at time 2n, Y2n n+S2n , then at some time i 2n, Yi = n+Si .
Proof: Let i be the first time at which Yi n + Si ; under the assumption
that n 2, i 1. So from the invariant, we cant have Yi = n + Si + 1,
and if Yi n + Si + 2, we have Yi1 Yi 1 n + Si + 1 n + Si1 ,
contradicting our assumption that i is minimal. The remaining alternative
is that Yi = n + Si , giving a collision at time i.
We now argue that Y2n n 1 is very likely to be at least n + S2n . Since
S2n is a sum of 2n independent 1 variables, from Hoeffdings inequality we
2
have Pr [Yn < n + S2n ] Pr [S2n n] en /4n = en/4 . For sufficiently
large n, this is much smaller than nc for any fixed c.
8
This is not the only possible algorithm, but there are a lot of plausible-looking
algorithms that turn out not to work. One particularly tempting approach is to run to
position n using the first n steps and then spend the next n steps trying to hit the target in
the immediate neighborhood of n, either by staying put (a sensible strategy when lost in the
woods in real life, assuming somebody is looking for you), or moving in a random walk of
some sort starting at n. This doesnt work if we want a high-probability bound. To see this,
observe that the target has a small but nonzero constant probability in the limit of begin
at some position greater than or equal to n + 4 n after exactly n/2 steps. Conditioned on
starting at n + 4 n or above, its chances of moving below n + 4 n 2 n = n + 2 n
4n/2(3n/2) 4/3
at any time in the next 3n/2 steps is bounded by e =e (Azuma), and a
similar bound holds independently for our chances of getting up to n + 2 n or above.
Multiplying out all these constants gives a constant probability of failure. A similar but
bigger disaster occurs if we dont rush to n first.
Appendix D
1. Your name.
(You will not be graded on the bureaucratic part, but you should do it
anyway.)
321
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 322
1. Show that both rejection sampling and range coding produce a uniform
value 0 s < n using an expected O(log n) random bits.
Solution
1. For rejection sampling, each sample requires dlg ne bits and is accepted
with probability n/2dlg ne 1/2. So rejection sampling returns a value
after at most 2 samples on average, using no more than an expected
2dlg ne < 2(lg n + 1) expected bits for the worst n.
For range coding, we keep going as long as one of the n 1 nonzero end-
points s/n lies inside the current interval. After k bits, the probability
that one of the 2k intervals contains an endpoint is at most (n 1)2k ;
in particular, it drops below 1 as soon as k = 2dlg ne and continues to
drop by 1/2 for each additional bit, requiring 2 more bits on average.
So the expected cost of range coding is at most dlg ne + 2 < lg n + 3
bits.
Solution
In principle, it is possible to compute this value exactly, but we are lazy.
m
For a lower bound, observe that after m rolls, each of the 2 pairs of rolls
has probability 1/n of being equal, for an expected total of m 2 /n duplicates.
For m = n/2, this is less than 1/8, which shows that the expected number
of rolls is ( n).
For the upper bound, suppose we have already rolled the die n times.
If we havent gotten a duplicate already, each new roll has probability at
least n/n = 1/ n of matching a previous roll. So after an additional n
rolls on average, we get a repeat. This shows that the expected number of
rolls is O( n).
Combining these bounds shows that we need ( n) rolls on average.
Solution
Let T (n) be the expected number of rounds remaining given we are starting
with n candies. We can set up a probabilistic recurrence relation T (n) =
1 + T (n Xn ) where Xn is the number of candies chosen by eactly one
child. It is easy to compute E [Xn ], since the probability that any candy gets
chosen exactly once is n(1/n)(1 1/n)n1 = (1 1/n)n1 . Summing over
all candies gives E [Xn ] = n(1 1/n)n1 .
The term (1 1/n)n1 approaches e1 in the limit, so for any fixed > 0,
we have n(1 1/n)n1 n(e1 ) for sufficiently large n. We can get a
quick bound by choosing so that e1 1/4 (for example) and then
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 324
There is a sneaky trick here, which is that we stop if we get down to 1 candy
instead of 0. This avoids the usual problem with KUW and ln 0, by observing
that we cant ever get down to exactly one candy: if there were exactly one
candy that gets grabbed twice or not at all, then there must be some other
candy that also gets grabbed twice or not at all.
This analysis is sufficient for an asymptotic estimate: the last candy gets
grabbed in O(log n) rounds on average. For most computer-sciency purposes,
wed be done here.
We can improve the constant slightly by observing that (1 1/n)n1 is
in fact always greater than or equal to e1 . The easiest way to see this is
to plot the function, but if we want to prove it formally we can show that
(1 1/n)n1 is a decreasing function by taking the derivative of its logarithm:
d d
ln(1 1/n)n1 = (n 1) ln(1 1/n)
dn dn
n 1 1
= ln(1 1/n) + .
1 1/n n2
and observing that it is negative for n > 1 (we could also take the derivative
of the original function, but its less obvious that its negative). So if it
approaches e1 in the limit, it must do so from above, implying (11/n)n1
e1 .
This lets us apply (F.3.1) with (n) = n/e, giving E [T (n)] e ln n.
If we skip the KUW bound and use the analysis in F.4.2 instead, we get
that Pr [T (n) ln n + ln(1/)] . This suggests that the actual expected
value should be (1 + o(1)) ln n.
2. For your choice of p above, what bound can you get on Pr [|D| E [|D|] t]?
Solution
1. First lets compute E [|D|]. Let Xv be the indicator for the event
that v D. Then Xv = 1 if either (a) v is in D1 , which occurs
with probability p; or (b) v and all d of its neighbors are not in D1 ,
which occurs with probability (1 p)d+1 . Adding these two cases gives
E [Xv ] = p + (1 p)d+1 and thus
X
E [|D|] = E [Xv ] = n p + (1 p)d+1 . (D.2.1)
v
1 e ln d/d
= lim
d ln d/d
1 1 ln d/d + O(ln2 d/d2 )
= lim
d ln d/d
ln d/d + O(ln2 d/d2 )
= lim
d ln d/d
= lim (1 + O(ln d/d))
d
= 1.
all 0,
!
e
Pr [S (1 + )] .
(1 + )1+
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 327
Solution
Let St = ti=1 Xi , sohthati S = Sn , and let t = ti=1 pi . Well show by
P P
Now apply the rest of the proof of (5.2.1) to get the full result.
Solution
1. Well compute the probability that any particular position i = 1 . . . n is
the start of a run of length k or more, then sum over all i. For a run of
length k to start at position i, either (a) i = 1 and Wi . . . Wi+k1 are
all 1, or (b) i > 1, Wi1 = 0, and Wi . . . Wi+k1 are all 1. Assuming
n k, case (a) adds 2k to E [Xk ] and case (b) adds (n k)2k1 , for
a total of 2k + (n k)2k1 = (n k + 2)2k1 .
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 328
2. We can get an easy bound without too much cleverness using McDi-
armids inequality (5.3.11). Observe that Xk is a function of the inde-
pendent random variables W1 . . . Wn and that changing one of these bits
changes Xk by at most 1 (this can happen in several ways: a previous
run of length k1 can become a run of length k or vice versa, or two runs
of length k or more separated by a single zero may become a single
2 run,
t
or vice versa). So (5.3.11) gives Pr [|X E [X]| t] 2 exp 2n .
We can improve on this a bit by grouping the Wi together into blocks
of length `. If we are given control over a block of ` consecutive bits
and want to minimize the number of runs, we can either (a) make
all the bits zero, causing no runs to appear within the block and
preventing adjacent runs from extending to length k using bits from
the block, or (b) make all the bits one, possibly creating a new run but
possibly also causing two existing runs on either side of the block to
merge into one. In the first case, changing all the bits to one except
for a zero after every k consecutive ones creates at most b `+2k1k+1 c
new runs. Treating each of the dne` blocks as a2 single variable
then
t
gives Pr [|X E [X]| t] 2 exp 2dn/`e(b(`+2k1)/(k+1)c)2 . Staring
at plots of the denominator for a while suggests that it is minimized at
` = k + 3, the largest value with
b(` + 2k 1)/(k + 1)c 2. This gives
t2
Pr [|X E [X]| t] 2 exp 8dn/(k+3)e , improving the bound on t
p p
from ( n log(1/)) to ( (n/k) log(1/)).
For large k, the expectation of any individual Xk becomes small, so wed
expect that Chernoff bounds would work better on the upper bound
side than the method of bounded differences. Unfortunately, we dont
have independence. But from Problem D.2.2, we know that the usual
Chernoff bound works as long as we can show E [Xi | X1 , . . . , Xi1 ] pi
for some sequence of fixed bounds pi .
For X1 , there are no previous Xi , and we have E [X1 ] = 2k exactly.
For Xi with i > 1, fix X1 , . . . , Xi1 ; that is, condition on the event
Xj = xj for all j < i with some fixed sequence x1 , . . . , xi1 . Lets call
this event A. Depending on the particular values of the xj , its not
clear how conditioning on A will affect Xi ; but we can split on the
value of Wi1 to show that either it has no effect or Xi = 0:
E [Xi | A] = E [Xi | A, Wi1 = 0] Pr [Wi1 = 0 | A] + E [Xi | A, Wi1 = 1] Pr [Wi1 = 1 | A]
2k Pr [Wi1 = 0 | A] + 0
2k .
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 329
Solution
Lets count the expectation of the number Xk of common subsequences of
length k. We have nk choices of positions in v, and nk choices of positions
Solution
This is a job for the Lovsz Local Lemma. And its even symmetric, so we
can use the symmetric version (Corollary 11.3.2).
Suppose we assign the non-blank symbols to each string uniformly and
independently at random. For each A S with |A| = k, let XA be the string
that has non-blank symbols in all positions in A. For each pair of subsets
A, B with |A| = |B| = k and |A B| = k 1, let CA,B be the event that XA
and XB are identical on all positions in A B. Then Pr [CA,B ] = mk+1 .
We now now need to figure out how many events are in each neighborhood
(CA,B ). Since CA,B depends only on the choices of values for A and B, it
is independent of any events CA0 ,B 0 where neither of A0 or B 0 is equal to A
or B. So we can make (CA,B ) consist of all events CA,B 0 and CA0 ,B where
B 0 6= B and A0 6= A.
For each fixed A, there are exactly (n k)k events B that overlap it in
k 1 places, because we can specify B by choosing the elements in B \ A
and A \ B. This gives (n k)k 1 events CA,B 0 where B 0 6= B. Applying
the same argument for A0 gives a total of d = 2(n k)k 2 events in
(CA,B ). Corollary 11.3.2 applies if ep(d + 1) 1, which in this case means
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 332
1. Show that any graph with m edges has a 3-way cut with at least 2m/3
edges.
Solution
1. Assign each vertex independently to S, T , or U with probability 1/3
each. Then the probability that any edge uv is contained in the cut is
exactly 2/3. Summing over all edges gives an expected 2m/3 edges.
Any payoff resulting from a bet must be a nonzero integer in the range
Xt to Xt , inclusive, where Xt is your current wealth.
The expected payoff must be exactly 0. (In other words, your assets
Xt should form a martingale sequence.)
For example, if you have 2 dollars, you may make a bet that pays off 2
with probability 2/5, +1 with probability 2/5 and +2 with probability 1/5;
but you may not make a bet that pays off 3, +3/2, or +4 under any
circumstances, or a bet that pays off 1 with probability 2/3 and +1 with
probability 1/3.
3. What strategy should you use to maximize the number of bets you
make before leaving?
Solution
1. Let Xt be your wealth at time t, and let be the stopping time when
you leave. Because {Xt } is a martingale, E [X0 ] = a = E [X ] =
Pr [X b] E [X | X b]. So Pr [X b] is maximized by making
E [X | X b] as small as possible. It cant be any smaller than b,
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 334
a b1
T (a) = a(b a 1) + 1+ T (b 2) . (D.4.1)
b1 b
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 335
When a = b 2, we get
b2 b1
T (b 2) = (b 2) + 1+ T (b 2)
b1 b
1 b2
= (b 2) 1 + + T (b 2),
b1 b
which gives
(b 2) 2b1
b1
T (b 2) =
2/b
b(b 2)(2b 1)
= .
2(b 1)
Plugging this back into (D.4.1) gives
a b 1 b(b 2)(2b 1)
T (a) = a(b a 1) + 1+
b1 b 2(b 1)
a a(b 2)(2b 1)
= ab a2 + a + +
b1 2(b 1)
3
= ab + O(b). (D.4.2)
2
This is much better than the a(b a) value for the straight 1 strategy,
especially when a is also large.
I dont know if this particular strategy is in fact optimal, but thats
what Id be tempted to bet.
Solution
1
1. For n > 0, we have n = 2 n1 + 38 n+1 , with a base case 0 =
1 3 3
8 + 8 0 + 8 1 .
The n expression is a linear homogeneous recurrence, so its solution
consists of linear combinations of terms bn , where b satisfies 1 =
1 1
2b + 38 b. The solutions to this equation are b = 2/3 and b = 2; we
can exclude the b = 2 case because it would make our probabilities
blow up for large n. So we can reasonably guess n = a(2/3)n when
n > 0.
1
For n = 0, substitute 0 = 8 + 38 0 + 38 a(2/3) to get 0 = 1
5 + 25 a. Now
substitute
1 = (2/3)a
1 3
= 0 + a(2/3)2
2 8
1 1 2 3
= + a + a(2/3)2
2 5 5 8
1 11
= + a,
10 30
which we can solve to get a = 1/3.
So our candidate is 0 = 1/3, n = (1/3)(2/3)n , and in fact we can
drop the special case for 0 .
Pn Pn n 1/3
As a check, i=0 n = (1/3) i=0 (2/3) = 12/3 = 1.
Solution
Its tempting to use the same coupling as for move-to-top (see 9.3.3). This
would be that at each step we choose the same card to swap to the top
position, which increases by at least one the number of cards that are in the
same position in both decks. The problem is that at the next step, these two
cards are most likely separated again, by being swapped with other cards in
two different positions.
Instead, we will do something slightly more clever. Let Zt be the number
of cards in the same position at time t. If the top cards of both decks are
equal, we swap both to the same position chosen uniformly at random. This
has no effect on Zt . If the top cards of both decks are not equal, we pick
a card uniformly at random and swap it to the top in both decks. This
increases Zt by at least 1, unless we happen to pick cards that are already in
the same position; so Zt increases by at least 1 with probability 1 Zt /n.
Lets summarize a state by an ordered pair (k, b) where k = Zt and b is
0 if the top cards are equal and 1 if they are not equal. Then we have a
Markov chain where (k, 0) goes to (k, 1) with probability nk n (and otherwise
stays put); and (k, 1) goes to (k + 1, 0) (or higher) with probability nk
n and
k
to (k, 0) with probability n .
n
Starting from (k, 0), we expect to wait nk steps on average to reach
(k, 1), at which point we move to (k + 1, 0) or back to (k, 0) in one more step;
n
we iterate through this process nk times on average before we are successful.
This gives an expected number of steps to get from (k, 0) to (k + 1, 0) (or
n n
possibly a higher value) of nk nk + 1) . Summing over k up to n 2
(since once k > n 2, we will in fact have k = n, since k cant be n 1), we
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 338
get
n2
n n
X
E [ ] +1
k=0
nk nk
n
!
X n2 n
= +
m=2
m2 m
!
2 2
n 1 + n ln n.
6
= O(n2 ).
So we expect the deck to mix in O(n2 log(1/)) steps. (I dont know if
this is the real bound; my guess is that it should be closer to O(n log n) as
in all the other shuffling procedures.)
Solution
Suppose we can make this chain reversible, and let be the resulting
stationary distribution. From the detailed balance equations, we have
(2/3)i = (1/3)i+1 or i+1 = 2i for i = 0 . . . m 2. The solution to
i
this recurrence is i = 2i 0 , which gives i = 2m21 when we set 0 to get
P
i i = 1.
Now solve 0 p0,m1 = m1 pm1,0 to get
m1 pm1,0
p0,m1 =
0
= 2m1 (2/3)
= 2m /3.
This is greater than 1 for m > 1, so except for the degenerate cases of
m = 1 and m = 2, its not possible to make the chain reversible.
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 339
Solution
1. First lets show irreducibility. Starting from an arbitrary configuration,
repeatedly switch the leftmost 0 to a 1 (this is always permitted
by the transition rules); after at most n steps, we reach the all-1
configuration. Since we can repeat this process in reverse to get to any
other configuration, we get that every configuration is reachable from
every other configuration in at most 2n steps (2n 1 if we are careful
about handling the all-0 configuration separately).
We also have that for any two adjacent configurations x and y, pxy =
1
pyx = 2n . So we have a reversible, irreducible, aperiodic (because
there exists at least one self-loop) chain with a uniform stationary
distribution x = 2n .
2. Here is a bound using the obvious coupling, where we choose the same
position in X and Y and attempt to set it to the same value. To
show this coalesces, given Xt and Yt define Zt to be the position of the
rightmost 1 in the common prefix of Xt and Yt , or 0 if there is no 1 in
the common prefix of Xt and Yt . Then Zt increases by at least 1 if we
1
attempt to set position Zt + 1 to 1, which occurs with probability 2n ,
and decreases by at most 1 if we attempt to set Zt to 0, again with
1
probability 2n .
It follows that Zt reaches n no later than a 1 random walk on 0 . . . n
with reflecting barriers that takes a step every 1/n time units on
average. The expected number of steps to reach n from the worst-case
3
Motivation: Imagine each bit represents whether a node in some distributed system
is inactive (0) or active (1), and you can only change your state if you have an active
left neighbor to notify. Also imagine that there is an always-active base station at 1
(alternatively, imagine that this assumption makes the problem easier than the other
natural arrangement where we put all the nodes in a ring).
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 340
The bound on 2 that follows from this is 8n6 , which is pretty bad
(although the constant could be improved by counting the (a) and
(b) bits more carefully). As with the coupling argument, it may be
that there is a less congested set of canonical paths that gives a better
bound.
Solution
1. Since every transition has a matching reverse transition with the same
transition probability, the chain is reversible with a uniform stationary
distribution H = 1/N .
(a) If Xt and Yt are both trees, then send them to the same tree
with probability 1/2; else let them both add edges independently
(or we could have them add the same edgeit doesnt make any
difference to the final result).
(b) If only one of Xt and Yt is a tree, with probability 1/2 scramble
the tree while attempting to remove an edge from the non-tree,
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 342
and the rest of the time scramble the non-tree (which has no
effect) while attempting to add an edge to the tree. Since the
non-tree has at least three edges that can be removed, this puts
(Xt+1 , Yt+1 in the two-tree case with probability at least 3/2m.
(c) If neither Xt nor Yt is a tree, attempt to remove an edge from
both. Let S and T be the sets of edges that we can remove from
Xt and Yt , respectively, and let k = min(|S|, |T |) 3. Choose k
edges from each of S and T and match them, so that if we remove
one edge from each pair, we also remove the other edge. As in
the previous case, this puts (Xt+1 , Yt+1 in the two-tree case with
probability at least 3/2m.
Solution
Essentially, were going to do the Karp-Luby covering trick [KL85] described
in 10.3, but will tweak the probability distribution when we generate our
samples so that we only get samples with weight w.
n
Let U be the set of assignment with weight w (there are exactly w such
assignments, where n is the number of variables). For each clause Ci , let
Ui = {x U | Ci (x) = 1}. Now observe that:
1 Initialize A[1 . . . n] to
2 Choose a hash function h
3 for i 1 . . . n do
4 x S[i]
5 if A[h(x)] = x then
6 return true
7 else
8 A[h(x)] x
9 return false
Algorithm D.1: Dubious duplicate detector
Its easy to see that Algorithm D.1 never returns true unless some value
appears twice in S. But maybe it misses some duplicates it should find.
1. Suppose h is a random function. What is the worst-case probability
that Algorithm D.1 returns false if S contains two copies of some
value?
2. Is this worst-case probability affected if h is drawn instead from a
2-universal family of hash functions?
Solution
1. Suppose that S[i] = S[j] = x for i < j. Then the algorithm will see x in
A[h(x)] on iteration j and return true, unless it is overwritten by some
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 344
value S[k] with i < k < j. This occurs if h(S[k]) = h(x), which occurs
with probability exactly 1 (1 1/n)ji1 if we consider all possible k.
This quantity is maximized at 1 (1 1/n)n2 1 (1 1/n)2 /e
1 (1 1/2n)/e when i = 1 and j = n.
2. As it happens, the algorithm can fail pretty badly if all we know is that
h is 2-universal. What we can show is that the probability that some
S[k] with i < j < k gets hashed to the same place as x = S[i] = S[j]
in the analysis above is at most (j i 1)/n (n 2)/n = (1 2/n),
since each S[k] has at most a 1/n chance of colliding with x and the
union bound applies. But it is possible to construct a 2-universal family
for which we get exactly this probability in the worst case.
Let U = {0 . . . n}, and define for each a in {0 . . . n 1} ha : U n by
ha (n) = 0 and ha (x) = (x + a) mod n for x 6= n. Then H = {ha } is 2-
universal, since if x 6= y and neither x nor y is n, Pr [ha (x) = ha (y)] = 0,
and if one of x or y is n, Pr [ha (x) = ha (y)] = 1/n. But if we use this
family in Algorithm D.1 with S[1] = S[n] = n and S[k] = k for
1 < k < n, then there are n 2 choices of a that put one of the middle
values in A[0].
2. Suppose that we insert x at some point, and then follow this insertion
with a sequence of insertions of new, distinct values y1 , y2 , . . . . Assum-
ing a worst-case state before inserting x, give asymptotic upper and
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 345
Solution
1. The probability of a false positive is maximized when exactly half the
bits in A are one. If x has never been inserted, each A[hi (x)] is equally
likely to be zero or one. So Pr [false positive for x] = Pr [Sk (3/4)k]
when Sk is a binomial random variable with parameters 1/2 and k.
Chernoff bounds give
2. For false negatives, we need to look at how quickly the bits for x are
eroded away. A minor complication is that the erosion may start even
as we are setting A[h1 (x)] . . . A[hk (x)].
Lets consider a single bit A[i] and look at how it changes after (a)
setting A[i] = 1, and (b) setting some random A[r] = 1.
In the first case, A[i] will be 1 after the assignment unless it is set back
1
to zero, which occurs with probability m/2+1 . This distribution does
not depend on the prior value of A[i].
In the second case, if A[i] was previously 0, it becomes 1 with probability
1 1 1 m/2
1 =
m m/2 + 1 m m/2 + 1
1
= .
m+2
So after the initial assignment, A[i] just flips its value with probability
1
m+2 .
It is convenient to represent A[i] as 1; let Xit = 1 if A[i] = 0 at time
t, and 1 otherwise. Then Xit satisfies the recurrence
h i m+1 t 1
E Xit+1 Xit = X Xt
m+2 i m+2 i
m
= Xit .
m + 2
2
= 1 Xit .
m+2
t
We can extend this to E Xit Xi0 = 1 2
Xi0 e2t/(m+2) Xi0 .
m+2
1
Similarly, after setting A[i] = 1, we get E [Xi ] = 1 2 m/2+1 = 1
4
2m+1 = 1 o(1).
Let S t = ki=1 Xht i (x) . Let 0 be the time at which we finish inserting x.
P
So for any fixed 0 < < 1 and sufficiently large m, we will have
E S = k for some t0 where t t0 k + t and t = (m ln(1/)).
t
We are now looking for the time at which S t drops below k/2 (the k/2
is because we are working with 1 variables). We will bound when
this time occurs using Markovs inequality.
t with E S t (3/4)k. Then E k S t
Lets look for the largest time
k/4 and Pr k S t k/2 1/2. It follows that after (m) k op-
erations, x is still visible with probability 1/2, which implies that the
expected time at which it stops being visible is at least ((m) k)/2.
To get the expected number of insert operations, we divide by k, to
get (m/k).
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 347
For the upper bound, apply the same reasoning to the first time at which
t
E S k/4. This occurs at time O(m) at the latest (with a different
constant), so after O(m) steps there is at most a 1/2 probability that
S t k/2. If S t is still greater than k/2 at this point, try again using
the same analysis; this gives us the usual geometric series argument
that E [t] = O(m). Again, we have to divide by k to get the number of
insert operations, so we get O(m/k) in this case.
Combining these bounds, we have that x disappears after (m/k)
insertions on average. This seems like about what we would expect.
Solution
Lets suppose that there is some such c. We will necessarily have c 1 = T (1),
so the induction hypothesis will hold in the base case n = 1.
For n 2, compute
n
!
n
2n
X
T (n) = T (k)
k=0
k
n1
!
n
= 2n T (n) + 2n nT (1) + 2n
X
T (k)
k=2
k
2n T (n) + 2n n + 2n (2n n 2)c.
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 348
n + (2n n 2)c
T (n)
2n 1
n
2 n 2 + n/c
=c .
2n 1
Solution
Suppose we have a monochromatic edge surrounded by non-monochrome
edges, e.g. RBRRBR. If we pick one of the endpoints of the edge (say
the left endpoint in this case), then the monochromatic edge shifts in the
direction of that endpoint: RBBRBRB. Picking any node not incident to a
monochromatic edge has no effect, so in this case there is no way to increase
the number of monochromatic edges.
It may also be that we have two adjacent monochromatic edges: BRRRB.
Now if we happen to pick the node in the middle, we end up with no
monochromatic edges (BRBRB) and the process terminates. If on the other
hand we pick one of the nodes on the outside, then the monochromatic edges
move away from each other.
We can thus model the process with 2 monochromatic edges as a random
walk, where the difference between the leftmost nodes of the edges (mod
APPENDIX D. SAMPLE ASSIGNMENTS FROM SPRING 2011 349
1 Randomly permute A
2 m
3 for i 1 . . . n do
4 if A[i] > m then
5 m A[i]
6 return m
Algorithm D.2: Randomized max-finding algorithm
Solution
Let Xi be the indicator variable for the event that Line 5 is executed on
the i-th pass through the loop. This will occur if A[i] is greater than A[j]
for all j < i, which occurs with probability exactly 1/i (given that A has
been permuted randomly). So the expected number of calls to Line 5 is
i = 1n E [Xi ] = ni=1 1i = Hn .
P P
Solution
The fact that G is itself a random graph is a red herring; all we really need
to know is that its d-regular.
1. Because G has exactly dn/2 edges, and each edge has probability 1/2
of being monochromatic, the expected number of monochromatic edges
is dn/4.
Solution
Color the elements in the final merged list red or blue based on which sublist
they came from. The only elements that do not require a comparison to
insert into the main list are those that are followed only by elements of the
351
APPENDIX E. SAMPLE ASSIGNMENTS FROM SPRING 2009 352
same color; the expected number of such elements is equal to the expected
length of the longest monochromatic suffix. By symmetry, this is the same as
the expected longest monochromatic prefix, which is equal to the expected
length of the longest sequence of identical coin-flips.
The probability of getting k identical coin-flips in a row followed by a
different coin-flip is exactly 2k ; the first coin-flip sets the color, the next k 1
must follow it (giving a factor of 2k+1 , and the last must be the opposite
color (giving an additional factor of 21 ). For n identical coin-flips, there is
a probability of 2n+1 , since we dont need an extra coin-flip of the opposite
color. So the expected length is n1 k + n2n+1 = Pn k + n2n .
P
k=1 k2 k=0 k2Pn
We can simplify the sum using generating functions. The sum k=0 2k z k
n+1
is given by 1(z/2)
Pn k k1 =
1z/2 . Taking the derivative with respect to z gives k=0 2 kz
n+1 2 n
(1/2) 1(z/2)
1z/2 + (1/2) (n+1)(z/2)
1z/2 . At z = 1 this is 2(1 2n1 ) 2(n +
1)2n = 2 (n + 2)2n . Adding the second term gives E [X] = 2 2 2n =
2 2n+1 .
Note that this counts the expected number of elements for which we do
not have to do a comparison; with n elements total, this leaves n 2 + 2n+1
comparisons on average.
Solution
We can show that the suggested sequence is a martingale, by computing
Xt+1 Xt Xt + 1 Yt Xt
E Xt , Yt = +
Xt+1 + Yt+1 Xt + Yt Xt + Yt + 1 Xt + Yt Xt + Yt + 1
Xt (Xt + 1) + Yt Xt
=
(Xt + Yt )(Xt + Yt + 1)
Xt (Xt + Yt + 1)
=
(Xt + Yt )(Xt + Yt + 1)
Xt
= .
Xt + Yt
h i
From the martingale property we have E XnX+Y n
n
= X0X+Y
0
0
. But Xn +
Yn = X0 + Y0 + n,
a constant,
so we can multiply both sides by this value to
X0 +Y0 +n
get E [Xn ] = X0 X0 +Y0 .
Solution
1. Any deterministic algorithm essentially just chooses some fixed number
m of tickets to collect before buying the placard. Let n be the actual
number of tickets issued. For m = 0, the competitive ratio is infinite
when n = 0. For m = 1, the competitive ratio is 3 when n = 1. For
m > 2, the competitive ratio is (m + 2)/2 > 2 when n = m. So m = 2
is the optimal choice.
Solution
This is a job for Chernoff bounds. For any particular machine, the load S is
a sum of independent indicator variables and the mean load is = n. So we
have
!n
e
Pr [S (1 + )] .
(1 + )1+
Observe that e /(1 + )1+ < 1 for > 0. One proof of this fact is to take
the log to get (1+) log(1+), which equals 0 at = 0, and then show that
d
the logarithm is decreasing by showing that d = 1 1+
1+ log(1 + ) =
log(1 + ) < 0 for all > 0.
So we can let c = e /(1 + )1+ to get a bound of cn on the probability
that any particular machine is overloaded and a bound of ncn (from the
union bound) on the probability that any of the machines is overloaded.
Appendix F
Probabilistic recurrences
F.2 Examples
How long does it take to get our first heads if we repeatedly flip
a coin that comes up heads with probability p? Even though we
probably already know the answer to this, We can solve it by solving
the recurrence T (1) = 1 + T (1 X1 ), T (0) = 0, where E [X1 ] = p.
355
APPENDIX F. PROBABILISTIC RECURRENCES 356
Suppose we start with n biased coins that each come up heads with
probability p. In each round, we flip all the coins and throw away the
ones that come up tails. How many rounds does it take to get rid of
all of the coins? (This essentially tells us how tall a skip list [Pug90]
can get.) Here we have E [Xn ] = (1 p)n.
Lets play Chutes and Ladders without the chutes and ladders. We
start at location n, and whenever its our turn, we roll a fair six-sided
die X and move to n X unless this value is negative, in which case
we stay put until the next turn. How many turns does it take to get to
0?
we pass. From the point of view of the interval [k, k + 1], we dont know
which n we are going to start from before we cross it, but we do know that
for any n k + 1 we start from, our speed will Rbe at least (n) (k + 1)
on average. So the time it takes will be at most kk+1 (t)
1
dt on average, and
the total time is obtained by summing all of these intervals.
Of course, this intuition is not even close to a real proof (among other
things, there may be a very dangerous confusion in there between 1/ E [Xn ]
and E [1/Xn ]), so we will give a real proof as well.
Proof of Lemma F.3.1. This is essentially the same proof as in Motwani and
Raghavan [MR95], but we add some extra detail to allow for the possibility
that Xn = 0.
Let p = Pr [Xn = 0], q = 1 p = Pr [Xn 6= 0]. Note we have q > 0
because otherwise E [Xn ] = 0 < (n). Then we have
E [T (n)] = 1 + E [T (n Xn )]
= 1 + p E [T (n Xn ) | Xn = 0] + q E [T (n Xn ) | Xn 6= 0]
= 1 + p E [T (n)] + q E [T (n Xn ) | Xn 6= 0] .
Now we have E [T (n)] on both sides, which we dont like very much. So
we collect it on the left-hand side:
(1 p) E [T (n)] = 1 + q E [T (n Xn ) | Xn 6= 0] ,
E [T (n)] = 1/q + E [T (n Xn ) | Xn 6= 0]
= 1/q + E [E [T (n Xn ) | Xn ] | Xn 6= 0]
"Z #
nXn1
1/q + E dt Xn 6= 0
a (t)
Z n Z n
1 1
= 1/q + E dt dt Xn 6= 0
a (t) nXn (t)
Z n
1 Xn
1/q + dt E Xn 6= 0
a (t) (n)
Z n
1 E [Xn | Xn 6= 0]
1/q + dt .
a (t) (n)
The second-to-last step uses the fact that (t) (n)f ort n.
It may seem like we dont know what E [Xn | Xn 6= 0] is. But we know
that Xn 0, so we have E [Xn ] = p E [Xn | Xn = 0] + q E [Xn | Xn 6= 0] =
APPENDIX F. PROBABILISTIC RECURRENCES 358
F.3.2 Quickselect
In Quickselect, we pick a random pivot and split the original array of size
n into three piles of size m (less than the pivot), 1 (the pivot itself), and
nm1 (greater than the pivot). We then figure out which of the three piles
contains the k-th smallest element (depend on how k compares to m 1) and
recurse, stopping when we hit a pile with 1 element. Its easiest to analyze
this by assuming that we recurse in the largest of the three piles, i.e., that
our recurrence is T (n) = 1 + max(T (m), T (n m 1)), where m is uniform
in 0 . . . n 1. The exact value of E [max(m, n m 1)] is a little messy to
compute (among other things, it depends on whether n is odd or even), but
its not hard to see that its always less than (3/4)n. So letting (n) = n/4,
we get
Z n
1
E [T (n)] dt = 4 ln n.
1 t/4
As it happens, this is the exact answer for this case. This will happen
whenever X is always a 01 variable1 and we define (x) = E [X | n = dxe],
which can be seen by spending far too much time thinking about the precise
sources of error in the inequalities in the proof.
Then we have
Z n
1
E [T (n)] dt
0+ (t)
n
X 1
=
k=1
(k)
P
n (n) 1/(n) 1/(k)
1 1/6 6 6
2 1/2 2 8
3 1 1 9
4 5/3 3/5 48/5
5 5/2 2/5 10
6 7/2 2/7 10 + (2/7)(n 5) = (2/7)n + 65/7
i.e., a statement of the form Pr [T (n) t] . There are two natural ways
to do this: we can repeatedly apply Markovs inequality to the expectation
bound, or we can attempt to analyze the recurrence in more detail. The first
method tends to give weaker bounds but its easier.
[ABMRT96] Arne Andersson, Peter Bro Miltersen, Sren Riis, and Mikkel
Thorup.
p Static dictionaries on AC0 RAMs: Query time
( log n/ log log n) is necessary and sufficient. In FOCS, pages
441450, 1996.
[AF01] David Aldous and James Allen Fill. Reversible Markov chains
and random walks on graphs. Unpublished manuscript, avail-
able at http://www.stat.berkeley.edu/~aldous/RWG/book.
html, 2001.
363
BIBLIOGRAPHY 364
[AS92] Noga Alon and Joel H. Spencer. The Probabilistic Method. John
Wiley & Sons, 1992.
[AS07] James Aspnes and Gauri Shah. Skip graphs. ACM Transactions
on Algorithms, 3(4):37, November 2007.
[BD92] Dave Bayer and Persi Diaconis. Trailing the dovetail shuffle to
its lair. Annals of Applied Probability, 2(2):294313, 1992.
[BRSW06] Boaz Barak, Anup Rao, Ronen Shaltiel, and Avi Wigderson.
2-source dispersers for sub-polynomial entropy and Ramsey
graphs beating the Frankl-Wilson construction. In Proceedings
of the thirty-eighth annual ACM symposium on Theory of com-
puting, STOC 06, pages 671680, New York, NY, USA, 2006.
ACM.
[CM03] Saar Cohen and Yossi Matias. Spectral bloom filters. In Alon Y.
Halevy, Zachary G. Ives, and AnHai Doan, editors, Proceed-
ings of the 2003 ACM SIGMOD International Conference on
Management of Data, San Diego, California, USA, June 9-12,
2003, pages 241252, 2003.
[FPSS03] Dimitris Fotakis, Rasmus Pagh, Peter Sanders, and Paul Spi-
rakis. Space efficient hash tables with worst case constant
access time. In Helmut Alt and Michel Habib, editors, STACS
2003, volume 2607 of Lecture Notes in Computer Science, pages
271282. Springer Berlin Heidelberg, 2003.
[GW12] George Giakkoupis and Philipp Woelfel. On the time and space
complexity of randomized test-and-set. In Darek Kowalski and
Alessandro Panconesi, editors, ACM Symposium on Princi-
ples of Distributed Computing, PODC 12, Funchal, Madeira,
Portugal, July 16-18, 2012, pages 1928. ACM, 2012.
[HH80] P. Hall and C.C. Heyde. Martingale Limit Theory and Its
Application. Academic Press, 1980.
377
INDEX 378