Discrete MathematicsProbability, Conditioning and Expectation9 of 9
Probability, Conditioning and Expectation · 9
Randomized Algorithms and Hashing
When an algorithm follows a fixed, predictable script, an awkward pattern in the data, or a deliberate attacker, can force it into its worst case on every step.
1
Beating the Adversary and Las Vegas Algorithms
Suppose we want to pick a number from the middle half of an unsorted list of 1,000,000 numbers without taking the time to sort the list.
Beating the Adversary and Las Vegas Algorithms
Text solution
Relate the first try to the remaining triesOn the first random pick, we either hit a green number with probability p and stop, or hit a red number with probability 1−p and still expect E more tries from the start.
E=first try1+if we miss, E more tries(1−p)E
Solve for the expected number of tries EExpand the right-hand side and subtract E from both sides so only the success probability p remains.
EpEE=1+E−pE=1=p1
Evaluate for the middle halfBecause half of the list sits in the middle two quarters, each random pick succeeds with probability p=21.
E=211=2 tries
So a Las Vegas search finds a middle-half number in 2 tries on average (or 10 tries if we narrow the target to the middle tenth where p=101), and it never returns a wrong number regardless of how the list is ordered.
An adversary can always move the smallest numbers under a fixed rule's arrows to make it fail, while a random pick still takes 2 tries on average because the fraction of green numbers on the board never changes.
Rearranging the list can trap any fixed rule on the smallest numbers, while a random pick still takes 2 tries on average because half the board stays green in every order.
2
Monte Carlo Algorithms and the Fermat Primality Test
A Las Vegas loop works when we can immediately verify a good item, but it doesn't work when we have to test a yes-or-no claim about an entire massive input, such as checking whether a box of a billion numbers is all zeros, or whether a 300-digit number n is prime. A Monte Carlo algorithm checks a fixed number of k random samples for a witness that disproves the claim, and concludes the claim is probably true if all k samples pass.
To test whether a giant integer n is prime without factoring it, we use Fermat's Little Theorem from modular arithmetic: if n is prime, then an−1≡1(modn) for every base a∈{1,2,…,n−1}. Taking the contrapositive of that conditional gives a witness test for compositeness: any base a with an−1modn=1 proves immediately that n is composite.
Monte Carlo Algorithms and the Fermat Primality Test
Text solution
Test n=9 with base a=2Compute 29−1mod9 to see whether a=2 breaks Fermat's condition.
29−1mod9=28mod9=256mod9=4=1(proves 9 is compositea=2 is a Fermat witness)
Test n=9 with base a=8Rewrite 8≡−1(mod9) before raising it to the 8th power.
89−1mod9=(−1)8mod9=1(fools the test for 9a=8 is a Fermat liar)
Bound the error after k random basesBecause at most half of the bases are liars for any non-Carmichael composite n, each independent test is fooled with probability at most 21.
Pr(fooled all k times)≤k independent tries21×21×⋯×21=(21)k
So a single witness (an−1modn=1) proves n is composite with 100% certainty, while 50 random bases that all return 1 leave at most a (21)50≈10−15 chance of being fooled by a composite number that isn't a Carmichael number.
3
Hash Functions and the Birthday Paradox
Now suppose we want to store a small set of records with huge keys, like 9-digit ID numbers, inside a small array of m slots (numbered 0 to m−1) so we can jump straight to any record's slot in one step. The simplest hash function compresses any large key x into a valid slot number by taking its remainder modulo m:
maps any integer x into {0,1,…,m−1}h(x)=xmodm
When two different keys x=y land in the same slot (h(x)=h(y)), we get a collision.
Hash Functions and the Birthday Paradox
Text solution
Multiply the collision-free probabilities for n=4 items in m=7 slotsEach new item must land in one of the remaining empty slots missed by the items placed before it.
Subtract from 1 to find the probability of at least one collisionAny outcome that is not completely collision-free has at least one pair of items sharing a slot.
Pr(at least one collision)=1−Pr(no collisions)=1−343120=343223≈65%
So even when a 7-slot table is nearly half empty with 4 items, a collision is already 65% likely (and with m=365 days, just n=23 people give a 50.7% chance of a shared birthday).
4
Separate Chaining, Linear Probing, and Load Factor
Because collisions happen long before a hash table is full, every hash table needs a collision rule and a measure of how crowded its slots are. The load factor α=mn measures the average number of stored keys per slot.
Separate Chaining, Linear Probing, and Load Factor
Text solution
Insert 10,19,26,14,33 into m=7 slots using linear probingStart at h(x)=xmod7 and step right through (h(x)+i)mod7 whenever a slot is already taken.
Find the expected collisions for a new key xDefine an indicator random variable Ii=1 if existing key yi lands in x's slot (so E[Ii]=m1) and 0 otherwise, then sum over all n keys by linearity of expectation.
E[collisions with x]=E[I1+I2+⋯+In]=E[I1]+E[I2]+⋯+E[In]=n existing keysm1+m1+⋯+m1=load factormn=α
So keeping α≤1 by doubling m whenever n reaches m keeps the expected chain length at most 1, giving O(1) average lookup time.
When colliding keys step right into a contiguous cluster, what happens when we delete a key from the middle of that cluster?
In linear probing, colliding keys step right into clusters, and deleted keys leave markers that searches step over and new keys reuse.
5
Universal Hashing
Our expected chain length of α=mn relied on the assumption that any two keys collide with probability m1. A single fixed hash function like h(x)=xmod7 cannot guarantee this on every input: if an adversary feeds the server multiples of 7(7,14,21,28,35), every key hashes to slot 0 and slows lookups from O(1) to O(n).
To defeat the adversary, universal hashing picks a hash function at random at startup from a family H designed so that any two distinct keys collide with probability at most m1.
Universal Hashing
Text solution
Pick a random function from the universal family at startupChoose a prime p larger than all possible keys, and draw a secret random multiplier a∈{1,2,…,p−1} and shift b∈{0,1,…,p−1}.
ha,b(x)=((ax+b)modp)modm
Bound the collision probability for any pair of distinct keysBecause a and b are chosen uniformly at random before any input arrives, even hand-picked multiples of m are scrambled modulo p before being reduced modulo m.
ha,b∈HPr(ha,b(x)=ha,b(y))≤m1for all x=y
So for every possible input list, each indicator variable satisfies E[Ii]≤m1, and the expected number of collisions in any slot stays at most α=mn.
Multiplying by a and shifting by b modulo p breaks up the spacing of the multiples 7,14,21,28,35, so for almost every pair (a,b) they no longer all land in the same slot.
Even when every input key is a multiple of 7, almost every hash function in the family keeps them from piling into one slot.
Key concepts
When an algorithm or data structure faces unknown or adversarial inputs, we choose how to use randomness based on whether we can afford a tiny chance of error or only a variable runtime:
Las Vegas vs. Monte Carlo
Use a Las Vegas algorithm when a candidate answer can be checked directly and the final answer must be 100% right; if each try succeeds with probability p, the expected number of tries is E=p1, and the probability of missing k times in a row is (1−p)k (for p=41,E=4 tries and 3 misses have probability (43)3). Use a Monte Carlo algorithm when checking the entire space is too slow and you test k random samples for a witness instead: a single witness proves the claim false with 100% certainty (such as 28mod9=4=1 proving 9 is composite), whereas k passes leave an error probability of at most (21)k. Do not use Fermat's test to prove a number prime with 100% certainty: a single base returning an−1modn=1 can be a Fermat liar like 88mod9=1.
Collisions and the Birthday Paradox
A hash function h(x)=xmodm maps keys into m slots. You only need n=m+1 keys for the Pigeonhole Principle to guarantee a collision with probability 1, but for n random keys the exact collision probability is
Pr(at least one collision)=1−mm⋅mm−1⋯mm−n+1
which already passes 50% near n≈m.
Handling collisions and load factor
Separate chaining stores colliding keys in a linked list at slot h(x), whereas linear probing steps through (h(x)+i)modm inside the array (leaving a `DELETED` marker on deletion so searches step over it while insertions overwrite it). Under uniform hashing (or universal hashing ha,b(x)=((ax+b)modp)modm, which keeps Pr(ha,b(x)=ha,b(y))≤m1 even against adversarial multiples of m), linearity of expectation gives an expected chain length of at most the load factor α=mn.
6
Practice
1
You want to pick a number strictly between the 40th and 65th percentiles (a band holding 25% of the data) from an unsorted array of 1,000,000 distinct numbers using a Las Vegas algorithm that picks an index uniformly at random and repeats until it hits a number in that range. How many tries does the algorithm take on average, and what is the probability that it still has not found a valid number after 3 tries?
Find the success probability p of a single pick from the percentile range, then use E=p1 for the average tries and multiply the single-try miss probability 1−p across 3 tries.
Find the expected number of triesSince 25% of the array lies strictly between the 40th and 65th percentiles, each random pick succeeds with probability p=41 (the total size 1,000,000 cancels out of the fraction).
E=p1=411=4 tries
Find the probability of missing 3 times in a rowEach try misses the target range with probability 1−p=43. Be careful not to raise the success probability p=41 to the 3rd power, which would give (41)3=641 (the chance of hitting three good numbers in a row).
Pr(3 misses)=(1−p)3=(43)3=6427≈42.2%
The algorithm takes 4 tries on average, and the probability it has not found a valid number after 3 tries is 6427 (about 42.2%).
2
A mystery box contains 10,000,000 numbers. Someone claims every number in the box is 0, and you know that if the box is corrupted, at least half of its numbers are non-zero. Using a Monte Carlo algorithm that inspects k randomly chosen numbers (with replacement), what can you conclude if the very first number you pull out is 9, and what is the smallest number of tries k needed so that if all k tries return 0, the probability you were fooled by a corrupted box is less than 1 in 500?
Checking powers of 2, watch out for stopping at k=8, which gives (21)8=2561>5001.
Distinguish between seeing a non-zero witness and seeing only zeros, then compare powers of (21)k against 5001.
Conclude from drawing a 9Because 9=0, it is a witness that disproves the claim immediately with 100% certainty (do not say it is only 50% certain; random error only applies when the sample returns 0).
Solve for the number of tries kIf the box is corrupted, at most 21 of the numbers are 0, so k draws of 0 happen with probability at most (21)k. Checking powers of 2, watch out for stopping at k=8, which gives (21)8=2561>5001.
(21)8(21)9=2561>5001=5121<5001
Drawing 9 proves with 100% certainty that the box is not all zeros, and you need k=9 tries to push the error probability below 1 in 500.
3
Use the Fermat Primality Test on the composite number n=15 by computing a14mod15 for the bases a=2 and a=4. Which of the two bases is a Fermat witness for 15, and which is a Fermat liar?
Notice that 24=16≡1(mod15) and 42=16≡1(mod15) to simplify the 14th powers quickly.
Test base a=2Use 24=16≡1(mod15) to reduce 214mod15. (Make sure to use the exponent n−1=14 rather than n=15.)
214mod15=((24)3⋅22)mod15≡(13⋅4)mod15=4=1
Test base a=4Use 42=16≡1(mod15) to reduce 414mod15.
414mod15=(42)7mod15≡17mod15=1
Classify each baseDo not mix up the two terms: a result different from 1 is a witness that proves 15 is composite, whereas a result of 1 is a liar that makes 15 look prime.
Base a=2 is a Fermat witness for 15, and base a=4 is a Fermat liar.
4
Suppose n=4 keys are hashed one by one into a table with m=10 slots, where each key independently picks one of the 10 slots uniformly at random. What is the exact probability of at least one collision, and how many keys must be inserted before the Pigeonhole Principle guarantees a collision with probability 1?
Do not stop at 0.504, which is the probability of zero collisions.
Multiply the probabilities that each of the 4 keys avoids the previous keys, and remember to subtract that product from 1.
Find the probability of no collisionsMultiply the fraction of empty slots available to each of the 4 keys in turn.
Subtract from 1 for at least one collisionDo not stop at 0.504, which is the probability of zero collisions.
Pr(at least one collision)=1−0.504=0.496(49.6%)
Apply the Pigeonhole PrincipleFilling all 10 slots takes 10 keys without forcing a collision, so you need m+1=11 keys (not 10) to guarantee a collision.
The probability of at least one collision is 0.496(49.6%), and 11 keys guarantee a collision with probability 1.
5
An initially empty hash table has m=7 slots (numbered 0 to 6) and uses h(x)=xmod7 with linear probing. Insert the keys 12,5,19,23,33 in that order, and then delete 19. Give the final contents of slots 0 through 6, and list the exact sequence of slots checked when searching for 33 and when searching for 40.
Compute xmod7 for each key, wrap around from slot 6 to slot 0 when probing, and place a `DELETED` marker when removing 19.
Insert the five keys and delete 19Since 12,5,19, and 33 all have xmod7=5 while 23mod7=2, they fill slots 5,6,0,2,1 in order, and deleting 19 replaces slot 0 with `DELETED`.
Trace the searches for 33 and 40Both start at 33mod7=40mod7=5. Do not treat slot 0 as empty when 19 is deleted (which would stop both searches at slot 0 and miss 33), and do not stop the search for 40 at slot 2 without checking the empty slot 3 that proves 40 is not in the table.
The final table is `[0: DELETED, 1: 33, 2: 23, 3: empty, 4: empty, 5: 12, 6: 5]`; searching for 33 checks slots 5,6,0,1 (found), and searching for 40 checks slots 5,6,0,1,2,3 (not found).
6
A hash table using separate chaining has m=50 slots and currently stores n=125 keys. Assuming each key lands in any slot with probability 501, what is the load factor α, how many existing keys is a new key x expected to collide with, and how many times must the table double its number of slots so that α≤1?
Divide the n=125 keys by the m=50 slots (do not invert the fraction to nm=12550=0.4).
Compute α=mn (items divided by slots), and check α after each doubling of m.
Compute the load factor and expected collisionsDivide the n=125 keys by the m=50 slots (do not invert the fraction to nm=12550=0.4). By linearity of expectation over the 125 indicator variables, the expected number of collisions for x equals α.
α=mn=50125=2.5 expected collisions
Double m until α≤1Doubling once gives m=100 slots with α=100125=1.25>1, so one doubling is not enough; doubling a second time gives m=200 slots.
αnew=200125=0.625≤1
The load factor is α=2.5, the new key is expected to collide with 2.5 keys, and the table must double 2 times.
7
To attack a table with m=5 slots and fixed hash function h(x)=xmod5, an adversary submits the keys 10,15,20, which all collide in slot 0. Suppose the server instead uses the universal family ha,b(x)=((ax+b)mod23)mod5 with prime p=23, and randomly picks a=7 and b=1 at startup. Which slots do 10,15,20 land in under h7,1, and before (a,b) is revealed, what upper bound does universal hashing guarantee on the probability that 10 and 15 collide?
Always reduce modulo p=23 before reducing modulo m=5 (skipping the mod23 step would leave (7x+1)mod5=1 for every multiple of 5).
For each key, compute (7x+1)mod23 first before taking the remainder modulo 5.
Evaluate h7,1(x)=((7x+1)mod23)mod5Always reduce modulo p=23 before reducing modulo m=5 (skipping the mod23 step would leave (7x+1)mod5=1 for every multiple of 5).