Chapter 9: Words and Mappings
Exercise 9.1
Imagine placing N labeled balls and M−1 distinct sticks in a row. The total number of arrangements is (N+M−1)!. Sticks are markers for urns. For example, |21||3 denotes a configuration where urns 0 and 2 are empty, urn 1 contains balls 2 and 1 (in this specific order) and urn 3 contains 3. Now, in our case both the balls and the sticks are indistinguishable. Therefore,
The general framework is known as the stars and bars method.
Exercise 9.2
Exercise 9.3
Exercise 9.4
In the previous exercise, we’ve already seen an instance of this, when the number of balls and urns equals N=M=2. It turns out, that it’s also the necessary and sufficient condition (assuming N,M≥1) for the average number of empty urns to equal the average minimum urn occupancy.
Let X be the average number of empty urns and Y be the average minimum urn occupancy. Since the probability of any single urn being empty is (1−M1)N, by linearity of expectation, the expected number of empty urns is
The average minimum occupancy can be computed using the tail sum formula of expectation
We are looking for conditions where X=Y.
If there are fewer balls than urns (N<M), at least one urn must be empty. Consequently, X>0 and Y=0, which means this situation cannot result in these quantities to be equal.
The case N=M⟹⌊N/M⌋=1, so Y simplifies to just the probability that every urn has exactly 1 ball; it’s the number of favorable permutations over the total configurations Y=MMM!. This gives
For any M≥3, the LHS definitely exceeds the RHS.
Finally, we must check the case N>M. Here, the expected number of empty urns decays exponentially toward 0, while the expected minimum occupancy grows toward roughly N/M. Because their trajectories are fundamentally different in the limit, they only intersect once. It can be shown that no integer solution exists for this intersection point, although the proof itself is out of scope of this manual.
Exercise 9.5
According to the estimate, it needs N∼2×365×ln100≈58 people, which slightly overestimates the true answer N=57 (acquired using a quick computer calculation).
Exercise 9.6 🌟
This exercise connects the expectation of the Ramanujan Q-function with the Rayleigh distribution. Furthermore, it presents a generalized formula to compute expectation of a random variable raised to nth power.
The variance is defined as Var(X)=E[X2]−(E[X])2. We already have the asymptotic expected value (the mean) from Theorem 9.1
The book A First Course in Probability by Sheldon Ross provides a handy formula to compute E[X2]. Its generalized form is
Based on Theorem 4.4 (Ramanujan Q-distribution), the probability of having no collisions after x throws can be estimated as
This gives
After plugging back the pieces into the variance formula we get
The standard deviation is
Apparently, it scales at the exact same rate as the mean and the median. The limit distribution of X/M is the Rayleigh distribution, which is right‑skewed. In any such distribution the long right tail pulls the mean to the right of the median. Because the shape of the distribution does not change as M grows—it simply stretches—the proportional difference between the mean and median remains constant. This is a fundamental property of the Rayleigh limit.
Exercise 9.7
The coefficients of z4 give back the counts from the above list (6 and 18).
Exercise 9.8 🌟
This exercise gives a detailed application of partial fraction decomposition using the limit method.
We want to find
The partial fraction decomposition gives the following structural form
Thankfully to the limit method, each Bk can be handled in a consistent and uniform manner
Plugging in z=M/k into the denominator, we get
Split the remaining product into positive and negative factorials
We now assemble Bk
Substitute Bk back into the sum for R(z). This gives
Exercise 9.9 🌟
This exercise demonstrates the inclusion-exclusion principle in action.
Let Ai be the event that a specific coupon i is missing from our collection after opening N−1 boxes. Therefore,
By the inclusion-exclusion principle, we’ve
The probability of missing a specific set of j coupons is (1−Mj)N−1. There are (jM) such combinations of size j, and the sign alternates based on (−1)j−1. After assembling the final formula, we get an equation very similar to the one from the previous exercise
Exercise 9.10
The text of this exercise is vague, assume that we need to find the EGF for M-surjections instead of surjections.
Let FM(z)=∑N≥0fNMzN/N! be our EGF for M-surjections, where fNM denotes the number of M-surjections of length N. The largest urn M may contain 1≤k≤N−M+1 balls. For any fixed k, the number of ways to form M-surjections of length N is
Now, we just need to sum over k
The RHS is a binomial sum operation, so
with the initial condition of F0(z)=1. The multiplicative factor of ez−1 is due to k being a positive integer (starts at 1). Iterating the equation, we get FM(z)=(ez−1)M, as expected.
Exercise 9.11
The next exercise shows that
The Python script below uses this formula to decide whether to print out the M-surjection or not. Another possibility would be to temporarily store words as they’re being generated and abort the process if the list becomes larger than the threshold. Otherwise, print the content of the list at the end.
Exercise 9.12
Based on Exercise 9.8 we’ve
Get a common denominator inside the power: (MM−j−1)N−1. Now, substitute the index k=M−1−j to get
which simplifies to
Because N−1 is just a placeholder for the number of items being partitioned, this identity holds for any generic exponent i.
We begin with the LHS in our exercise (recall that N![zN]ejz=jN from Table 3.4)
Exercise 9.13
The EGF immediately follows from Table 3.6, but we can easily derive it using the symbolic method. A partition of elements into indistinguishable nonempty groups (subsets) can be structurally defined as a set of nonempty sets of elements. This can be expressed as
Exercise 9.14
Wikipedia has the full proof.
Exercise 9.15
This directly follows from marking the inner sets by u (see Exercise 9.13). Therefore,
The coefficient uk represents partitions into exactly k subsets. The size of those individual subsets is tracked by the z variable.
Exercise 9.16
The book contains a typo. The correct recurrence is FNM=∑k=0N(kN)F(N−k)(M−1).
Here, the functional equation is simpler than in Exercise 9.10 (with the same initial condition). This gives
Let u mark the alphabet size M, and let's construct F(z,u)=∑M≥0FM(z)uM. We can establish the following relationship from the functional equation
This is equivalent to
Now, we can derive the requested BGF
Exercise 9.17
The EGF for M-words with all letter frequencies even is (see Table 3.3 in the book)
Exercise 9.18
The EGF for an urn requiring >k balls is ez−∑i=0ki!zi. The lowest order term in this series is (k+1)!zk+1. When we raise this EGF to the power of M, the very first non-zero term is
This gives
Using Theorem 9.3, the EGF for an urn with <(k+2) balls is ∑i=0k+1i!zi. We want to extract the coefficient for M(k+1)−1 from this EGF raised to the power of M. To build zM(k+1)−1 from the product of M polynomials (where the max term is zk+1), we are forced to pick the zk+1/(k+1)! term exactly M−1 times and the zk/k! term exactly once. There are M ways to choose which of the M polynomials contributes the zk term. Therefore, the extracted coefficient multiplied by (M(k+1)−1)! and M is
Exercise 9.19 🌟
This exercise builds upon the analysis of the birthday paradox and showcases an interesting fact about collisions in hash tables.
The text of this exercise asks us to derive a formula for N urns, but we’ll denote the number of urns with M to retain consistency.
Let X be the number of balls thrown until the second collision occurs. The expected value can be computed using the tail sum formula
Theorem 9.1 speaks in terms of UNTIL condition, whilst this exercise mentions BEFORE. Asymptotically there is no difference, but in discrete terms we have E[Before]=E[Until]−1.
The probability that there are no collisions when N balls are thrown into M urns is given by Theorem 9.1. Therefore,
If exactly 1 collision occurred in N throws, it means exactly N−1 distinct urns are occupied. One urn contains exactly 2 balls, and the other N−2 urns contain exactly 1 ball. Thus,
This gives
The first sum is (see Theorem 9.1) ∼2πM. To solve the second sum, let's rewrite it
Now, we proceed similarly as in Exercise 9.6
The integral is listed as of similar form of the standard Gaussian integral on Wikipedia.
The total expected time until the second collision is the sum of both parts ∼232πM. It tells us that asymptotically, getting the second collision takes roughly 50% longer than getting the first one.
Exercise 9.20
The text of this exercise asks us to derive a formula for N urns, but we’ll denote the number of urns with M to retain consistency.
We can repeat more or less the same math as in the previous exercise to conclude that the leading asymptotic term remains intact. Instead, let’s argue in a different way. At the time the first collision happens, we have thrown ∼M balls. At this exact moment, the board looks like this:
Exactly 1 urn has 2 balls.
Roughly M urns have exactly 1 ball.
The probability that the next thrown ball hits the single urn that already has 2 balls is 1/M. The probability it hits one of the urns with 1 ball (triggering our new definition of a collision) is roughly MM=M1. Because M1 is massively larger than M1 as M→∞, it’s overwhelmingly statistically likely that the "next" collision will hit a 1-ball urn rather than the 2-ball urn. The events we’re trying to ignore (balls falling into urns with more than 2 balls) are so extremely rare, at this stage of the process, that they don’t affect the leading asymptotic term!
Exercise 9.21 🌟
This exercise demonstrates the multinomial theorem in action.
The book already defines for us the EGF for words comprising at most k occurrences of each of M different letters. Here, we have k=2
We need to find the explicit expression for the number of words, which is N![zN]FM(z). Using the multinomial expansion, the EGF is
Substitute k1=N−2k2, which also forces k0=M−N+k2. This gives
Let k be the number of letters that appear exactly twice. We can pick N−k distinct letters in (N−kM) ways from an alphabet of size M. Among these, we can select (kN−k) to be duplicates. Finally, there are N!/2k ways to reorder them. Summing over all k gives our explicit formula.
Exercise 9.22
This is a variation of the previous exercise with M=365. The probability of not having a triplet is
We can computationally evaluate this exact coefficient extraction to build the curve shown below.

Exercise 9.23
The plot from the previous exercise already gives the answer for three people. The explicit formula for the probability of not having a four-person shared birthday is
It turns out, that crossing the 50% threshold for four people with shared birthday happens at N=187.
Exercise 9.24 🌟
This exercise introduces the double dixie cup problem.
Let X be the number of balls thrown until every urn has at least 2 balls. The event X≤N means that after exactly N throws, all M urns contain at least two balls. Theorem 9.4 from the book immediately gives
Therefore, the average number of balls thrown into M urns before each urn is filled at least twice is
Intuitively, we might think that filling every urn with at least 2 balls takes x2 times as much as filling them with 1 ball. But this is obviously not the case. By the time we finally fill the last empty urn, all the others already contain more than one ball. Filling them a second time requires barely any extra effort.
Exercise 9.25 🌟
This model is the direct "dual" to the double dixie cup work (see the previous exercise). While the dixie cup problem looks at the expected time N to reach a certain occupancy, this model looks at the expected occupancy for a fixed time.
Let X be the random variable representing the minimal occupancy (the number of balls in the least-filled urn) when distributing N balls into M urns. Theorem 9.4 gives
If we multiply the average value with the total number of combinatorial objects, then we get the CGF
The following Python code tabulates the values for M and N less than 20. The function count_valid_distributions uses dynamic programming and recurrence from Exercise 9.16 to maintain required precision and accuracy.
Exercise 9.26 🌟
This exercise highlights the utility of indicator random variables in solving combinatorial problems (see also the next exercise). They can also give an idea how to formally describe the corresponding combinatorial class using the symbolic method.
This problem can be easily solved using indicator random variables Ii for each position in the word
We know that E[I1]=Pr{I1=1}=1, since the first block is always new. For the other blocks
as M−1 different characters may be at the previous position. If the current letter is different, then it starts a new block. The total number of blocks in the entire word is X=∑iIi. The average number of blocks of contiguous equal elements in a random word is
As a quick sanity check, the predicted average for Table 9.2 in the book is 3, which perfectly matches the data.
Modeling via BGF
For the sake of completeness, let’s develop the BGF for this problem using the symbolic method. The average can be computed by using Table 3.5 from the book (we already know the answer).
Observe, that we mark blocks (nonempty contiguous equal elements). We’ve M choices for the first block and M−1 for all subsequent ones. The BGF immediately follows from the corresponding transfer theorem
Exercise 9.27
Let's look at any adjacent pair of letters wi and wi+1 from an M-letter alphabet. Since the word is completely random, there are M2 possible pairs for these two positions. We can partition them into three categories:
wi<wi+1 (rise)
wi>wi+1 (fall)
wi=wi+1 (flat continuation)
Because of symmetry, the number of rising pairs exactly equals the number of falling pairs. Specifically, out of the M2 pairs, exactly M of them are flat (the two letters are the same). The remaining M2−M pairs are evenly split between rises and falls. Therefore, the number of rising/falling pairs is 2M2−M=(2M).
The probability of a rise at any specific position i is
There are N−1 adjacent pairs in a word of length N. Let Ii be an indicator random variable that equals 1 if a rise occurs at position i. By the linearity of expectation and symmetry
A run is a maximal contiguous subsequence of elements. We’ve to be careful about whether a run is strictly increasing or non-decreasing. Let’s use the latter. The first letter always starts a fresh run. A new run starts at position i+1 if and only if wi>wi+1 (a fall). The expected number of non-decreasing runs is
This definition is aligned with the similar property of runs and falls for permutations, as explained in the book.
Exercise 9.28
The probability is 100×100−100=100−99. We can sum the individual probabilities, as the events for different urns are mutually exclusive (only one urn can possibly hold all balls).
Exercise 9.29
The probability is 100!×100−100, since we have 100! possible mappings of balls to urns.
Exercise 9.30
Since we are tracking empty urns, we set k=0. Substituting this into the EBGF from the book (see the subsection about alternative derivations), we get
Let U be the number of empty urns. We get
The second derivative of F evaluated at u=1 is
The total cumulated cost of pairs of empty urns is
Using Table 3.5 from the book, we are ready to plug in all parts into the variance formula
Using ln(1−x)∼−x−x2/2, let's expand the terms for N/M=α>0 fixed as N,M→∞.
Therefore,
The quadratic expectation term is
The book already provides E[U], thus,
Put all three expanded pieces back into the variance formula
Thus, the standard deviation is
Exercise 9.31 🌟
This exercise counterbalances the approach with indicator random variables; it showcases why EGFs are so incredibly powerful. Trying to solve this with discrete indicator variables or inclusion-exclusion principle would be a combinatorial nightmare.
The EGF for a single urn is (see Table 3.3 in the book)
The EGF for M urns is simply an M-sequence of the above EGF
The total number of valid distributions is
Therefore, the probability that each urn will contain an even number of balls when N balls are distributed among M urns is
Quick Sanity Check of our Formula
If N is odd, then it’s impossible to divide an odd number of balls into a sum of strictly even numbers. So, the probability must be exactly 0. Interestingly, this is handled for us automatically by the EGF machinery. The binomial coefficient is symmetric, so (jM)=(M−jM). Let’s see what do we get by summing such symmetric entries (for N odd, (−x)N=−xN)
They annihilate each other, hence the total sum is zero. When M is even, we also have one singular term for j=M/2, but this trivially evaluates to zero.
Exercise 9.32
CNk[M] represents the total number of M-words of length N such that a specific letter occurs exactly k times. Assume N≥k. The base case is C00[M]=1. The recurrence relationship follows from the following observations:
We can select M−1 different letters for expanding the M-words of length N−1 already containing k occurrences of a specific letter.
We can append a letter to M-words of length N−1 containing k−1 occurrences of that letter.
The Python script below computes these values.
Exercise 9.33
We need to use Theorems 6.6 (see also Exercise 6.37) and 9.6 from the book.
As the official errata points out, the formulae in Theorem 9.6 are different than those given in Table 9.9. Therefore, the results below eesentially illustrate the methodology, which is the most important part of the whole story.
In case of an unsuccessful search, we have:
For N=1000 we want 1000/M≤2H1001−2⟹M≥78.
For N=106 we want 106/M≤2H106+1−2⟹M≥37334.
In case of a successful search, we have:
For N=1000 we want 999/(2M)≤2H1000−3+2H1000/1000⟹M≥42.
For N=106 we want (106−1)/(2M)≤2H106−3+2H106/106⟹M≥19391.
In essence, the analysis highlights the general relationship: to beat a binary search tree of size N, we need a hash table of size M=Ω(lnNN).
Exercise 9.34 🌟
This exercise introduces a powerful concept in probability theory called the law of total variance.
Let S be the random variable representing the number of comparisons (probes) for a successful search. Imagine we pick one of the N keys in the table uniformly at random. We want to find the search cost for this specific key. Let X be the number of other keys that hashed into the exact same list as our target key. Since each of the remaining N−1 keys had an independent p=1/M chance of landing in this list, X perfectly follows a binomial distribution. From this, we know the mean and variance of X:
E[X]=(N−1)p
Var(X)=(N−1)p(1−p)
If there are X other keys in the list, the total length of the chain is X+1. Because our target key is equally likely to have been inserted at any position in this chain, the search cost S given X is uniformly distributed on the integers {1,2,…,X+1}. For a discrete uniform distribution on 1,…,n, the mean is 2n+1 and the variance is 12n2−1. Substituting n=X+1, we get our conditional moments:
E[S∣X]=2X+2=1+2X
Var(S∣X)=12(X+1)2−1=12X2+2X
According to the law of total variance, we have
Let’s compute the pieces
Adding them together and simplifying, we get
This gives the standard deviation of the number of comparisons required for a successful search in hashing with separate chaining
Exercise 9.35 🌟
This exercise is a case study how to analyze optimization techniques, like in this case, keeping the chains sorted. Without developing a mathematical model, we may never be sure do we have a good or bad idea.
Sorting the lists does absolutely nothing to improve the average cost of a successful search! If a key is actually in the table, we still have to traverse the list until we find it. Because its rank among the keys in that list (chain) is perfectly uniform, we’ll search exactly as far on average as we would in an unsorted list. Therefore, keeping the chains sorted is a mechanism specifically designed to optimize unsuccessful searches.
Let X be the number of keys that hashed into the exact same list as our search key. Let P be the number of comparisons (probes) we make. The conditional average is
The bolded X in the above formula represents the case of hitting the end of the list.
To find the unconditional average E[P], we use the fact that the number of keys in any list perfectly follows a Poisson distribution in the asymptotic limit N,M→∞ with α=Np=N/M:
Shifting to a Poisson distribution drastically simplifies the calculus without impacting the asymptotic conclusions. For example, E[X+11]=∑kk+11k!αke−α=∑k(k+1)!αke−α=αe−α∑k(k+1)!αk+1=αe−α(eα−1)=α1−e−α. Computing this expectation whilst sticking to the exact binomial distribution would be a nightmare.
According to the law of total expectation, we have
Obviously, sorting cuts, on the average, the search time by half. Of course, this must be balanced with the cost of maintaining the chain sorted. In practice, this almost never worths the effort.
We also need
This gives (we know that E[X]=Var(X)=α)
Now, we can compute the standard deviation as Var(P)=E[P2]−(E[P])2
Exercise 9.36
In the section about the expected maximum occupancy of urns, the book claims that the length of the longest list when Program 9.1 is used will be ∼lnN/lnlnN, on the average. If we compute two hash functions and put the key on the shorter of the two lists, then the longest list drops to O(lnlnN), on the average, with high probability. The details are given in the paper Balanced Allocations.
Exercise 9.37
The Cayley function is defined as C(z)=zeC(z) (see Theorem 6.14 in the book). We’ve to extract a coefficient from a function composed with an implicitly defined generating function. Therefore, we need to use the 3rd case of the Lagrange inversion theorem with g(u)=eαu and f(u)=u/eu. This gives
Exercise 9.38 🌟
This exercise introduces Abel’s binomial theorem and shows how GFs help in proving seemingly daunting identities.
The LHS follows from the previous exercise
The RHS is a classical convolution of GFs, where we also reuse the result from the previous exercise. We’ve
Now, we just need to equate and simplify the LHS and RHS to get
Exercise 9.39
Since "average search cost" can refer to either finding a key that is in the table (successful) or verifying a key is not in the table (unsuccessful), we cover both scenarios based on Table 9.9 from the book. The objective is to find the point where the cost equals lnN.
The threshold for a successful search is
Substituting α≡N/M and solving for N, we get the implicit equation
The threshold for an unsuccessful search is handled in virtually the same manner. Thus,
Exercise 9.40
Program 9.2 will enter an infinite loop, which means the cost is infinite.
Evaluating the exact formula from Table 9.9 for this edge case gives back a finite value. The reason is that the precondition N<M is violated, hence the output is meaningless.
Exercise 9.41
We want to construct the EGF with respect to N, treating the table size M as a fixed parameter. The method is virtually the same as in the case of a successful search demonstrated in the book. This gives
Exercise 9.42
The "solution" is given in the matching footnote in the book.
When you build an EGF using the symbolic method, the structures must physically make sense. It must natively encode the hard stop at N=M while simultaneously yielding a clean, infinite-series function. Here is the pertinent citation from the book regarding the explicit EGF for a successful search:
This is not directly meaningful for linear probing because the quantities are defined only for N ≤ M but it would seem a fine candidate for a combinatorial interpretation.
We had encountered a similar situation with CFGs (see Exercise 8.35). Employing BGFs may solve the spatial constraints.
Nonetheless, there is another fundamental issue. An inability of the symbolic method's grammar to directly specify the historical averaging process. Deriving the successful search cost requires performing a discrete integration over the timeline of the table's construction; it was computed in the book by averaging all unsuccessful searches that happened while building the table. But this is evidently a step outside the symbolic framework to finish the math.
Some attempts have already been made with the combinatorial structure called an increasing tree to track history. The problem with linear probing is that disjoint clusters can merge over time and this introduces global dependencies that are difficult to handle.
I think, that aggressively forcing some method beyond its capabilities could jeopardize the core principles that were in place originally. Even if new operators and extensions may encompass the above features, it could be at the expense of comprehensibility and succinctness of the current grammar. This is reminiscent to an old battle in computer science with every domain specific language: "Should it be more powerful?" Once a DSL becomes Turing complete, abuses of the grammar happen, and things start to fall apart. One notable example is the C++'s templating engine, that inadvertently became overly capable. Now, a simple syntax error in a template can generate hundreds of lines of incomprehensible compiler errors.
Exercise 9.43
Let’s use the symbolic method applied to the occupancy model (see Theorem 9.5). The EBGF for a single integer (urn) is ϵ+u×SET>0(Z)=1+u(ez−1). Because the mapping consists of N independent urns (the elements of the image), the EBGF for the entire mapping is simply the single-urn EBGF raised to the power of N. This gives
It’s easy to verify the correctness of this EBGF by extracting the coefficient of ukN!zN. Expanding the binomial and applying the identity from Table 3.6 for Stirling numbers of the second kind gives
Now, performing the previous transformations in an opposite direction, starting from the formula for CNk, we can arrive at the EBGF CN(z,u).
Exercise 9.44
See the previous exercise, which actually combines two approaches inside a single solution.
Exercise 9.45
While the above equation is the exact direct recurrence, it introduces a division by N−k. When programming this to generate a table, floating-point division can lead to precision errors for large combinatorial integers. Let’s use the substitution DNk=CNk/(kN). We can leverage again the following two identities:
(kN)=N−kN(kN−1)
(kN)=kN(k−1N−1)
This gives DNk=kD(N−1)k+kD(N−1)(k−1). The following Python script produces the table of mappings for N<20.
Exercise 9.46
The explicit expression is
The combinatorial reasoning is analogous to the number of mappings, as explained in the book.
Exercise 9.47
A random N-mapping is any function f with the integers 1 to N as both domain and range. Run the following procedure:
Initialize an empty set S and a current value u=u0 (seed).
While u∈/S:
Insert u into S
Set u=f(u)
Because S can hold a maximum of N distinct integers, the while loop can run a maximum of N times. Upon the (N+1)th iteration (at the absolute latest), u must evaluate to a number already in S by the Pigeonhole principle. The loop terminates, and the cycle is found.
Exercise 9.48
The following Python script reports some properties about the specified random mappings for various input sizes.
It produces the following output:
A truly uniform random mapping has an image ratio 1−1/e≈0.632, on the average. This follows from the corollary of Theorem 9.5 with α=1 pertaining to the expected number of empty urns. Thus, a random mapping will leave about 36.8% of the range completely empty.
Exercise 9.49 🌟
This exercise introduces the principle of deferred decisions, a powerful technique in analyzing randomized algorithms.
Imagine we’re constructing our random mapping f:1,2,…,N→1,2,…,N dynamically, rather than generating the whole thing up front. Starting from an arbitrary seed x0, we generate subsequent values on the fly, essentially simulating each time an independent roll of an N-sided die.
The isomorphism to the birthday problem is based on the following observations:
In the mapping, the table size is N. In the birthday problem, it’s the N days of the year.
In the mapping, we’re taking a step to a new node xk. In the birthday problem, it’s a new person walking in.
In the mapping, we hit a cycle the moment f outputs a node xj we’ve already visited. In the birthday problem, we stop the moment a person announces a birthday that someone else in the room already has.
Let T be the number of distinct nodes visited (the rho length) before closing the cycle. Let B be the number of people in the room before the first shared birthday is found. Their probability distributions are identical
The book contains, at the time of this writing, an unreported errata. Namely, the fomula in Theorem 9.9 should read as Pr{rho length>k}=(NN−1)(NN−2)…(NN−k).
Using the tail sum formula for expectation, we can also conclude that
Exercise 9.50
The minimal rho length is achieved for identity mapping, resulting in the rho length of N. The maximal length is attained for a random mapping being a permutation with one cycle. The length in this case is N2.
The minimal tree length is achieved for a random mapping being a permutation; all tails are empty, so the length is zero. The maximal length is attained for a random mapping being a single linear chain tree that terminates in a fixed point. The length is N(N−1)/2.
Exercise 9.51
The next Python script computes the relevant statistics. The theoretical asymptotic estimates are based on Theorem 9.10 and Table 9.12 from the book. The averages are reported as seen from a random point.
The program generates the following output:
Exercise 9.52
Wikipedia covers the topic of cycle detection in some detail. It presents several algorithms that may answer the query of this exercise using only O(1) extra space for a random point. Iterating over all points and summing the results provides the required answer.
Exercise 9.53
The linear time algorithm using linear extra space is depicted below. For clarity the two stages are kept separate, although they could be bundled to avoid traversing the array twice.
Exercise 9.54
The next Python script uses the union-find data structure to track groups and their sizes (see also the previous exercise). The find method employs path compression to improve performance.
The program generates the following output:
The computed averages nicely align with the prediction from Table 9.12 even for small N.
Exercise 9.55 🌟
This exercise formally introduces the pointing operator Θ of the symbolic method. It was used many times before, but here it has a special combinatorial role.
There are several derivation stages that build upon the idea of looking at random mappings as sets of cycles of Cayley trees.
The Structural Decomposition (the "Rho" Shape)
To find the expected rho length of a random point, we first need to isolate a single, random node in the mapping. This is called a pointed mapping. When you point to a random node x and trace its path, it forms a sequence of nodes (the tail) that eventually falls into a cycle. Let's break this pointed path down into Cayley trees:
The Tail: The path from x to the cycle is effectively a branch of a tree. If this path has t nodes, it is structurally equivalent to a sequence of exactly t trees rooted along the path.
The Cycle: The cycle has some length c. The node where the tail meets the cycle accounts for 1 tree. The remaining nodes in the cycle correspond to a sequence of c−1 trees.
Notice that the total number of trees forming this entire backbone is t+c−1. Therefore, the rho length is exactly equal to the total number of trees in this specific pointed component.
Formulation of the BGF
The EGF that enumerates cycles of trees (unpointed components) is from the book
UN is the number of valid cycles of trees you can build using N nodes. Let’s apply the pointing operator Θ on U(z) to enumerate pointed components. This gives
Combinatorially, PN=NUN counts the total number of pointed connected components of size N. For every single one of those unpointed components, there are exactly N different nodes you could choose to point to.
If we expand P(z) as a geometric series, we get ∑kkC(z)k. The power k represents the number of trees in the component. Since we just proved that the number of trees equals the rho length, we can mark trees by substituting C(z) with uC(z). We’ve
Combinatorially, PNk counts the number of pointed connected components of size N where the pointed node has a rho length of exactly k.
But why is the coefficient k in P(z)=∑kkC(z)k? There are exactly k different ways to split a sequence of k trees into "the tail" and "the cycle." This is why a component with a rho length of k has exactly k valid structural configurations! Observe that by pointing to a node we break the symmetry of a cycle (dividing by k disappears in U(z)) and we allow a sequence of k trees to form k distinct rho shapes. Again, the unit of abstraction is a complete Cayley tree, thus all sub-branching is handled internally and tracked by z.
A pointed mapping consists of exactly one pointed component and a set of unpointed components. The EGF for the set of unpointed components is given in the book
Our final BGF is the product of these two GFs
Combinatorially, MNk counts the number of random N-mappings, containing a pointed node, where the rho length of that pointed node is exactly k.
Asymptotic Estimation
The total sum of rho lengths across all possible mappings is
We should use here the general singularity analysis method of analytic combinatorics. We know the Cayley tree function has a dominant singularity at z=1/e, where its Taylor expansion behaves as:
Let's evaluate H(z) near this singularity. This gives
We’re now ready for the final assembly by leveraging Stirling’s approximation of N!
Dividing this total by N, we get the average rho length of a random point.
Exercise 9.56
Based on the result of Exercise 9.48, we know that the image ratio for the first iteration is 1−1/e, therefore the size of the input for the second iteration is k=N(1−1/e). Using the same logic, the new image ratio is 1−e−k/N. Thus, the average number of different integers in the image when a random mapping is iterated twice is N(1−e−1+1/e)≈0.47N.
Exercise 9.57
This is documented as OEIS A001372.
Exercise 9.58 🌟
This exercise introduces a handy variant of the Lagrange inversion theorem that avoids the derivative form (3rd case).
In a standard mapping, every single node has an out-degree of exactly 1. Consequently, every path is guaranteed to eventually lead to a cycle. In a partial mapping, some nodes have an out-degree of 0. These nodes act as "sinks" where the path simply stops.
This splits the graph into two entirely distinct types of connected components, which is best illuminated by the following symbolic expression (a Cayley tree is denoted by TC):
We can use the alternative variant of the Lagrange inversion theorem
where ϕ(u)=u/f(u)=eu and g(u)=eu. In our case, ϕ′(u)/ϕ(u)=1. This immediately gives
Exercise 9.59
By defining a sequence of 2N integers strictly bounded between 1 and N, the mapping f forces a "layered" topological structure:
The Core 1≤x≤N: These N nodes map exclusively to other nodes in the same range, so they form a standard random N-mapping.
The Periphery N+1≤x≤2N: These N nodes also map into the core range. Because no node can ever map to them, they are guaranteed to be absolute leaves (nodes with an in-degree of exactly 0).
Assume that "path length" means the total sum of the tree path lengths (the number of steps to reach a cycle) for all 2N nodes. Let TN be the total tree path length of a standard random N-mapping. We know from Table 9.12 that its expected value is
Every peripheral node j takes exactly 1 step to enter the core (by landing on its target f(j)). Once it lands there, it simply inherits the remaining path length of that target node. Therefore,
Adding together the two pieces and simplifying gives
The average path length as seen from a random point is the total divided by 2N.
Exercise 9.60
The next Python script empirically verifies the statistics given in Table 9.12.
It produces the following output:
Exercise 9.61
Modern PRNGs, like Mersenne Twister, don’t have short cycles. Therefore, the Python script below use less capable generators to demonstrate the issue of short cycles, although it does showcase a linear congruential generator whose image spans the range (this was mentioned in the book). The cycle detection algorithm is the one from Exercise 9.52.
It produces the following output:
Exercise 9.62
See the previous exercise. The middle-square method is famous for collapsing into extremely short cycles or hitting zero.
Exercise 9.63
The next script demonstrates how "collapses" occur for non prime modulus. For a prime N, all values of c produce an expected result O(N), on the average. The strangest behavior happens for a power of prime. At any rate, instead of averaging over many randomly selected values of c, the program shows how various choices influence the simulated random mapping.
The program creates the following report:
Exercise 9.99*
The text of this exercise is available at the book’s website; it’s not in the book, but it should be. The EGF that defines random mappings with no singleton cycles, as a function of the Cayley function, is
The alternative variant of the Lagrange inversion theorem (see Exercise 9.58) immediately gives
The last step follows by letting N→∞.
Last updated