taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 1.2.10-7

Exercise 1.2.10-7

not stated yet in Lean solution written

RatingM27
MarkersM (mathematical)
KindK7, analyze: find the mean, the variance or the distribution of a cost from the written solution
SectionSection 1.2.10 of Volume 1. Companion chapter: Analysis of an algorithm

The task

Find the distribution of AA when the nn keys contain exactly mm distinct values and are otherwise random.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Only the rightmost occurrence of each value can make M4 run.

Hint 2

Fix the pattern of equal values, and see what remains random.

Solution

Show the solution

Assume that the values are 1,…,m1,\ldots,m, that each occurs at least once, and that all such sequences are equally likely. (Only the relative order of the values matters for Algorithm M.)

Step M4 runs for position kk exactly when X[k]>X[i]X[k]>X[i] for all i>ki>k. If the value X[k]X[k] occurs again at a position to the right of kk, this fails. So only the rightmost occurrence of each value counts. Let the rightmost occurrences be at the positions r1<r2<⋯<rmr_1<r_2<\cdots<r_m, and let π=(X[r1],…,X[rm])\pi=(X[r_1],\ldots,X[r_m]), a permutation of 1,…,m1,\ldots,m. The values at the other positions are not larger than values to their right in a way that matters: a non-rightmost occurrence of a value vv has vv to its right, so it never counts. Hence AA equals the number of times M4 runs when Algorithm M works on π\pi alone.

Now sort the sequences by the partition of the positions 1,…,n1,\ldots,n into the mm classes of equal value. Each partition into mm classes comes from exactly m!m! sequences, one for each assignment of the values 1,…,m1,\ldots,m to the classes, and the permutation π\pi runs through all m!m! permutations once. So within each partition π\pi is uniformly random, and AA has the distribution of Section 1.2.10 for mm keys:

Pr⁡(A=k)=pmk=1m![mk+1],\Pr(A=k)=p_{mk}=\frac1{m!}\left[{m\atop k+1}\right],

for every n≥mn\ge m, and it does not depend on the partition or on nn.

Check

Take n=5n=5, m=3m=3. All 35−3⋅25+3=1503^5-3\cdot2^5+3=150 sequences with each of 1,2,31,2,3 are enumerated by Python. The distribution of AA is 13,12,16\frac13,\frac12,\frac16 for A=0,1,2A=0,1,2, which is p3kp_{3k}.

Remarks

The result changes when more is known, for example the numbers of copies of each value (Exercise 1.2.10-18). The mean of AA is Hm−1H_m-1.

This solution is drafted, and a person has not reviewed it yet. The source.

In Lean

not stated yet The exercise is not stated in Lean yet.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.