Chapter 8: Strings and Tries
Exercise 8.1
As mentioned in the book, satisfies the same recurrence as the generalized Fibonacci numbers of Exercise 4.18. This gives
The other one can be derived from the formula of Theorem 8.2 by rearranging terms
Now, we extract the coefficient of on both sides. For the RHS is 0, thus
Remember that represents the number of bitstrings of length with no runs of consecutive 0s. If the length of a bitstring is strictly less than , it’s physically impossible for the string to contain a run of consecutive 0s. Therefore, every possible bitstring of length is valid. The initial values are
Observe that can be calculated from the first recurrence, so the second one becomes fully defined, too.
Exercise 8.2
We need to solve the following inequality
with . Using a computer algebra system and Table 8.3, we get .
Exercise 8.3
This time we should rely on the asymptotic formula from the previous exercise (with the RHS of 0.5), as exact calculations based on recurrence would become prohibitively slow. The parameters are (these can be attained using a computer algebra system):
We get .
Exercise 8.4 🌟
We start with the formula from Theorem 8.2 and extract the coefficient . We can do this by expanding the rational function into a power series using the geometric series formula and the binomial theorem. Let’s rearrange terms
This gives
We can transform into a geometric series and expand
We want to find the coefficient of a general term . This gives
We have
Now we substitute and into our general coefficient formula to solve our original equation
Putting everything together, we get
Exercise 8.5
Let’s build our BGF using the symbolic method; designates a class of bitstrings with leading 1s (which may be zero). The beauty of this approach is that the construction itself fully describes the underlying combinatorial decomposition, so everything is explicit. We have
Notice that we must mark the leading 1s. This translates to
Now, we simply follow the recipe laid out in Table 3.5 in the book to find the moments (mechanical steps are omitted):
,
.
Exercise 8.6
We just apply Theorem 8.2 and its corollary to get
Exercise 8.7 🌟
Let be our BGF, where marks the length of the string and marks the length of the longest run of 0s. Instead of trying to directly find the generating function for bitstrings where the longest run is exactly , it’s much easier to think about boundaries. A bitstring has a longest run of 0s that is if and only if it has no runs of consecutive zeros. Therefore, the OGF for strings whose longest run of 0s is is exactly . This gives
We can now sum over all and multiply by to get
Exercise 8.8 🌟
Let be the random variable denoting the position of the end of the first run of 0s ("wait time"); the length of the bitstring (prefix) is the random variable itself. The book establishes the relationship
To compute the variance we need a different paradigm than the BGF method and Table 3.5. Because the thing we are measuring is already the length of the bitstring, we don't need a second variable . We can extract everything we need directly from . Let's define a new generating function for these tail probabilities
The second corollary of Theorem 8.2 says that
To find the variance, besides the mean, we need the second factorial moment . We’ve
Equate this quantity with the one derived in a different manner. Let’s differentiate both sides of our basic equation and evaluate it at . This gives
Substitute everything into the standard variance identity (see Section 1.7 in the book)
Plugging everything into the above formula and simplifying, we get
Therefore,
Exercise 8.9
The next Python script generates the plot by evaluating the GF from the book.

Exercise 8.10 🌟
The second corollary of Theorem 8.2 specifies the expected length of the bitstring (i.e., the expected position where the pattern finally ends). Because of the way the nested for loops work in Program 8.1, the algorithm re-examines characters whenever a partial match fails. This means the number of bits examined will be strictly greater than the expected length of the string.
We can view our random bitstring as a sequence of "failed blocks" followed by one "success block." A failed block can be described as , where . Processing such a failed block demands bit comparisons (a total of subsequent partial and failed matches). Processing the final 0s requires additional bit comparisons.
The probability of seeing consecutive 0s from an arbitrary position is . We can model the run of our program as a series of Bernoulli trials with probability of success. The random variable denoting the number of failures before the first success is governed by the geometric distribution. Its expected value is .
Now, what is the probability that a failed block has exactly zeros? The unconditional probability of reading exactly 0s and then 1 is simply . The total probability of any failure occurring (meaning we hit 1 before 0s) is the sum of these probabilities for all valid . Thus,
The conditional probability of seeing the pattern , given that the block is a failure
The expected number of comparisons per failed block
Now, we can express the total expected number of comparisons on failed blocks, relying on Wald's equation
The exact expected number of bits examined to find the first run of 0s is
Exercise 8.11
This is a simple application of the corollary of Theorem 8.3:
,
,
,
.
Exercise 8.12
To find the pattern that appears earliest, we need to minimize . Since always starts with a 1, the absolute smallest it can possibly be is just . This happens when a pattern has zero internal overlaps—meaning no prefix matches any suffix. We’ve seen such patterns in the previous exercise.
Patterns consisted of all 0s or 1s are likely to appear the latest. They’re maximally autocorrelated, so is maximized.
Exercise 8.13
The standard deviation does depend on the pattern, because the expected value is dictated by the pattern's autocorrelation polynomial , the spread of that distribution (the variance and standard deviation) is fundamentally locked to that same polynomial. Following the steps from Exercise 8.8, we can see that the standard deviation depends both on and .
Exercise 8.14 🌟
The GF for the number of strings over an -character alphabet that do not contain the specific pattern of length is
The expected position of the end of the first occurrence of a -character pattern with autocorrelation polynomial is given by .
In our case, , and . Therefore, the expected number of characters typed before the monkey hits upon the given phrase is .
Exercise 8.15
This is a variation of the previous exercise. The pattern has some overlaps, so
Since and , the expected number of characters typed before the monkey hits upon the given phrase is .
Exercise 8.16
Table 8.6 already provides an answer for height no greater than 4. The following list gives the remaining OGFs and REs:
,
(1(1(1(1(10)*0)*0)*0)*0)*, ,,
(1(1(1(1(1(10)*0)*0)*0)*0)*0)*, .
Exercise 8.17 🌟
Theorem 8.3 says that the GF is
Finding a regular expression for strings avoiding a pattern is notoriously complex because REs are generative (they build strings) rather than restrictive. Unfortunately, there is no reverse mapping from an OGF back to unambiguous RE. We’ll model the pattern-matching process as a DFA and leverage Arden's Theorem.
101101. Because we are looking to avoid the pattern, any string that reaches state 6 (Trap) stays there and is essentially rejected. All other states are accepting.The system of equations for the given DFA is
Solving it and simplifying leads to
Here is the translation of this RE into a form recognized by tools. The + operator is a syntactic sugar for one or many, while the original + is replaced with the | symbol. Notice that the expression is anchored to capture the entire content.
Exercise 8.18
The word disjoint means that the second search starts after the first match is "consumed." Since the bitstring is generated randomly, the sequence of bits generated after the first match is statistically identical to a brand new, entirely independent random bitstring. Therefore, due to this independence (memoryless property), the average position of the end of the second disjoint string of 0s is exactly double the expected position of the first occurrence
Exercise 8.19
The RE 0*00 is unambiguous, so there is only one way to derive a string of 0s.
The RE 0*00* allows possibilities. Observe that the number of 0s taken on the first position completely determines the number of 0s on the last one, and vice versa. The zero in the middle is forced, so we can choose between 0 and for the first occurrence of 0*.
Exercise 8.20
Exercise 8.21
Table 8.5 lists all 4-bit patterns together with their waiting times. The expected number of 0s appearing before the first occurrence of each of the bit patterns of length 4 in a random bitstring is exactly half of their waiting times, minus the number of 0s in the patterns themselves. This gives
Group 1: Wait Time = 30
0000:1111:
Group 2: Wait Time = 16
0001:1000:0011:1100:0111:1110:
Group 3: Wait Time = 18
0010:0100:0110:1001:1011:1101:
Group 4: Wait Time = 20
0101:1010:
Exercise 8.22
Seemingly the answer follows directly from the second corollary of Theorem 8.2. But the situation is a bit more complicated, since we must allow any sort of alternating 0s and 1s to appear. For example, a monkey may start with one type (010101...) and switch to another (101010...) in the middle. These events could happen in any order. Because these two strings share so many prefixes, waiting for "whichever comes first" is significantly faster.
We can solve this by translating the bits into a sequence of transitions. Let’s create a new sequence where 1 means a different key was typed than before and zero if the same key was hit. Therefore, waiting for any alternating string of bits is mathematically identical to waiting for a solid block of 1s in a random bitstring. Now, we can apply the second corollary of Theorem 8.2. Since a sequence of transitions requires actual keystrokes (a starting character must be there before we can transition away from it), we need to add 1 to the total. The answer is .
Exercise 8.23
The book explicitly lists state 0 at front as a starting point. The state transitions are (including that extra 0 at the beginning)
The following Python script prints out these transitions for the given pattern in the book.
Exercise 8.24
This is a variation of the previous exercise. The state transitions are
Exercise 8.25
Once we reach state 2 in 2 steps, we need additional 3 steps to reach it again. Therefore, the text string of length 25 that maximizes (among all strings of length 25) the number of times the KMP automaton from Figure 8.3 reaches step 2 is
Notice that the solution isn’t unique.
Exercise 8.26

Exercise 8.27
The program from Exercise 8.23 (the DFA table and the function call arguments should be changed) generates the following output:
Exercise 8.28
For the pattern 101010... the state transition table is (listed horizontally as ordered pairs): (0, 1), (2, 1), (0, 3), (4, 1), ... , (0, 2k-1), (2k, 1).
For the pattern 010101... the state transition table is (listed horizontally as ordered pairs): (1, 0), (1, 2), (3, 0), (1, 4), ..., (2k-1, 0), (1, 2k).
Exercise 8.29
Notice that any occurrence of 0 or 2 would reset the automaton (bring it back to state 0). The pattern resembles the one from the previous exercise, so the transition table is similarly constructed (drawn vertically):
The program from Exercise 8.23 should be altered to reflect the new DFA table and text string. It produces the following output:
Exercise 8.30 🌟
Let's assume we’ve a DFA with states, numbered to . Let state be the start state and be the OGF that enumerates all valid paths starting from state and ending in an accept state. The language recognized by the entire DFA is simply .
A valid string starting from state is formed by taking exactly one transition (which costs one character, or ) to a neighboring state (could also be a self-transition), and then appending any valid string from state . We can write this as a linear equation for every state
where:
is the number of transitions from state to state (usually 0 or 1, but could be more if multiple characters lead to the same state).
if state is an accept state (since the empty string is a valid way to stop right there), and otherwise. Exercise 8.17 shows how to apply this in practice.
As usual, a system of such linear equations is most easily handled in matrix form. Let be the column vector of our OGFs, be the column vector of our accept states, and be the adjacency matrix of the DFA. This gives
The solution is
Cramer's rule for matrix inversion says that
The matrix contains only linear polynomials. The determinant of a matrix of polynomials is calculated purely by adding and multiplying those polynomials. Therefore, the denominator is guaranteed to be a polynomial in . Finally, the adjugate matrix is formed by calculating the determinants of sub-matrices. Thus, every entry in the numerator is also guaranteed to be a polynomial in .
Because (the OGF of our language) is calculated strictly by dividing a polynomial numerator by a polynomial denominator, it is by definition a rational function. This concludes the proof.
Exercise 8.31
The following Python script implements the solver for the model presented in the previous exercise. To showcase that it works properly, it’s setup to reproduce the OGF from Exercise 8.17.
It outputs exactly the same OGF as formulated in Theorem 8.3, although not in the most simplified form.
Exercise 8.32
The number of bitstrings of length with equal number of 0s and 1s is given in the book
We just need to count all possible even length prefixes (including an empty prefix) with equal number of 0s and 1s and divide the result by the total number of bitstrings of length . This gives
Exercise 8.33
This directly follows from Exercise 6.10, where denotes the length of a random bitstring
Exercise 8.34
The first question can be answered by employing linearity of expectation. Let be an indicator random variable that a prefix of length has more 0s than 1s. Therefore,
The answer to the second question follows from generalizing an approach from Exercise 6.10, where was fixed at 1. So, by renaming variables, adjusting the criteria for the lower bound, and setting the touching line to , we get
Exercise 8.35 🌟
A stack with a fixed capacity of is mathematically identical to a deterministic FSA with exactly states. A push is a transition from state to state . A pop is a transition from state to state . If we’re in state 0 and read a pop, it's a trap (reject). If we’re in state and read a push, it's a trap (reject). Push and pop operations may be encoded as 1 and 0, or vice versa. Therefore, the problem transforms into tracking random bitstrings of length , where the number of 0s and 1s remain bounded.
We cannot use a ballot like CFG, since it’s impossible to specify an upper limit. It could only model a stack of infinite capacity. Let’s see what do we get if we plug an adjacency matrix for into the program from Exercise 8.31. The new input is
It outputs the OGF for Fibonacci numbers
Let’s try with the following setup
The program gives
It turns out that the growth rate for the total number of legal sequences is dictated by the maximum eigenvalue of the adjacency matrix. At any rate, to get the desired probability we must divide this amount by .
Exercise 8.36 🌟
Let our operations be:
: Insert (1 choice)
: Remove (2 choices: or )
We can reuse the idea from Figure 8.2 in the book by placing any valid sequence into an envelope of one insert and remove operations. This gives our CFG
The initial condition is , so
If we use a substitution , then it immediately transforms into the familiar OGF for Catalan numbers. Thus,
The number of legal sequences of length is exactly . The number of all possible sequences is (recall that we have 3 operations). Therefore,
Exercise 8.37
We build upon the previous exercise. A new nonterminal is <T> which designates a potentially traced (inspected) sequence. The Inspect (Watch) operation is denoted by W. This gives
The grammar results in the following system of equations:
We can immediately solve the second equation
It’s a left shifted OGF for Motzkin numbers (see Chapter 6 of the book about -restricted trees). Thus,
The probability that a random sequence of operations of length is legal is
Exercise 8.38
Observe that the number of legal balanced sequences matches the enumeration of general Catalan trees. This bijection follows from the parenthesis system representation of those trees. Therefore, we can find the total probability of success by evaluating the at . This gives
This is remarkable, that a monkey has only a 50% chance of succeeding. Nonetheless, the expected number of keystrokes is even more dizzying. We have
The average number of characters typed before the monkey hits upon a legal balanced sequence is
Exercise 8.39 🌟
The experiment terminates the exact moment the monkey types a palindrome of 10 or 11 characters long. We’ll spawn two gamblers at every step :
Gambler A brings $1 and bets that the 10 characters from to will form a length 10 palindrome.
Gambler B brings $1 and bets that the 11 characters from to will form a length 11 palindrome.
To form a length 10 palindrome, 5 independent pairs of characters must match. Gambler A waits for the first 5 characters to be typed, and then bets their fortune on the 6th character matching the 5th, the 7th matching the 4th, etc. Every time they are right, their money multiplies by 26. Gambler B also requires exactly 5 pairs to match (the center character is free). At any rate, the maximum winning amount is .
Since we "work" with 2 gamblers at a time, we have
where is a random variable denoting the stopping time. When the game stops at time , it stops because either a length 10 or length 11 palindrome was just reached.
If it stops on a length 10 palindrome, then Gambler A who arrived 10 steps ago wins the grand prize of . If it stops on a length 11 palindrome, then Gambler B who arrived 11 steps ago wins the grand prize of . Gamblers who arrived very recently, and haven't finished their 10 or 11 characters yet, are "unresolved" with expected earning of $1. There are such gamblers from both groups. The total payout is .
Because the total expected payout is unconditionally the same regardless of whether the monkey triggers the length 10 or length 11 condition, we can solve directly for the expected number of keystrokes
The methodology laid out above easily generalizes to any .
Exercise 8.40 🌟
Since spaces can appear anywhere in a regular expression they aren’t essential for evaluating the validity of a sequence. The monkey is typing "essential" keys with probability 31/32, and "noise" (spaces) with probability 1/32. By Wald's Lemma (see Exercise 8.21), we can completely remove the space key from the board. We simply calculate everything in terms of a 31-key keyboard and then multiply the result by 32/31, the expected number of total keystrokes required to produce one essential keystroke, to account for the spaces typed in between.
Let's build the unambiguous CFG for a standard regular subexpression over the 30 essential keys (excluding space and period). Every binary operation brings its own parentheses to guarantee unambiguous parsing, while the unary star operator does not need them. We’ve
The final language becomes (notice the period at the end). Theorem 8.6 gives
Because the regular expression is enclosed in strict parentheses and ends with a unique period that never appears anywhere else, the language is prefix-free, suffix-free, and internally non-overlapping. Therefore, we can regard every keystroke as a Bernoulli trial, so the expected waiting time is simply the reciprocal of the total probability mass of (expectation of the geometric distribution). We’ve
This gives our waiting time (the expected number of characters typed before the monkey hits upon a legal regular expression)
Exercise 8.41
000 is contained within the bitstring 00011. Finally, nonvoid external nodes are shown with full bitstrings for clarity, although remaining suffixes could work, too.Exercise 8.42
Exercise 8.43
Assume that the same structure means the same arrangement of internal nodes. This entails that leaves must be associated with 2 nonvoid external nodes. We can vary how the remaining void external nodes may turn into nonvoid ones.
The leftmost trie has configurations. The middle has configurations. The rightmost trie is full, so the given configuration is unique.
Exercise 8.44 🌟
For any given trie with external nodes, we can have configurations, where counts the number of leaves in (see also the previous exercise). To generalize the enumeration for any (in the spirit of Figure 8.6 in the book) we should derive the corresponding BGF.
The book already defines (see Chapter 5 or the book’s website) such that tracks internal nodes and tracks leaves. For a tree with external nodes, there are exactly internal nodes. Our combinatorial rule states that for a given tree with external nodes and leaves, the number of configurations is . Thus, we can find the total number of trie configurations by evaluating at and multiplying the coefficient by . Let's define a raw generating function that applies this transformation
We need to check the boundary condition for . The empty tree in is represented by 1. Thus,
It turns out, that it reports 2 tries, whereas from Figure 8.6 we have . The discrepancy emanates from being discriminatory regarding void and nonvoid external nodes. To perfectly match to Figure 8.6, we simply subtract that extra empty-set configuration
Now, we’re left with truly mechanical work to find the closed-form equation. We can execute the algebra starting directly from the book's equation
After applying substitutions, multiplying by the previously mentioned factor, solving the quadratics for , and finally subtracting , we get (the algebraic steps are omitted to keep the exposition tidy)
Using WolframAlpha we can expand the OGF to see the first few terms
It perfectly matches Figure 8.6 and, in principle, we can find any coefficient. We can also find the growth rate of coefficients by transforming
Now, we can directly apply the corollary of Theorem 5.5 (see the book's website) with and to get
Exercise 8.45 🌟
Essentially, this is a variation of the previous exercise. To track the void nodes, we want a BGF where marks all external nodes and marks only the void ones. In a trie with external nodes and leaves, external nodes are toggleable. Each can be nonvoid (weight 1) or void (weight ), contributing a factor of . In the previous exercise this was 2, since we didn’t care to further classify them. The polynomial tracking the configurations of this specific shape is
Now, the derivation virtually follows the steps from the previous exercise. We have
The boundary condition here requires us to subtract , since an empty trie is a single nonvoid external node. Solving the equation gives
Let be the CGF for the total number of void nodes across all tries of size (see Table 3.5 in the book)
The expected proportion of void nodes in a random trie of size is
The above estimate follows by employing the corollary of Theorem 5.5 on
We already know from before the estimate of .
Exercise 8.46
Let be the number of strings in the set (which equals the number of nonvoid external nodes). Let be the number of distinct prefixes (including the empty prefix ) shared by at least two strings in the set (which equals the total number of internal nodes, because every shared prefix forces a split). We also know that in any binary tree (including tries) the number of external nodes is . Hence, the number of void external nodes is simply . Consequently, we have a void external node if this amount is positive.
Exercise 8.47
If we use 1-based indexing then the last position to be examined is 29, since both patterns are 10 bits long. To compute the total number of bits examined, it’s best to group distinct prefixes that occur at all possible positions and handle them separately. For example, a single 0 entails 1 bit comparison to hit a void external node. 11 needs 2 bit comparisons, since both patterns start with 10 (the mismatch happens at the second bit). The total sum is 73 bit comparisons.
Exercise 8.48
The basic variant revolves around searching for multiple patterns in a text using a trie. We first build a trie from the set of pattern strings. Set the counter to zero. For every valid position in the text perform a search and increase the counter whenever a nonvoid external node is encountered.
The improved version would use an altered Aho-Corasick FSA, where we simply need to treat the accepting states exactly like the internal states. Every visit to the corresponding accept state would also increment the counter. Figure 8.8 in the book shows a halting machine.
Exercise 8.49
Exercise 8.50
Exercise 8.51 🌟
Exercise 8.52 🌟
We proceed as in the proof of the corollary of Theorem 4.10 in the book. The recurrence can be simplified to
Multiplying by and summing on leaves a straightforward convolution where the EGF must satisfy the functional equation
Iterating the equation, we find that
Using Table 3.4 from the book, we get
Now, we proceed exactly as in the proof of Theorem 8.8 by first approximating the sum
We split this sum at . Let's call this boundary . By shifting the index of summation below , the bounds of our two sums become and .
In the derivation, we’ve used the following equations:
Our sum is essentially of the form , where
Observe that is a periodic function, since . By the laws of Fourier analysis, any periodic function can be represented as its mean value plus a fluctuating wave. This gives
We’ve used the substitution , so . The integral can be evaluated in WolframAlpha resulting in 1. Therefore,
Exercise 8.53
The next Python script computes the values of using Numpy and produces the plot shown below.

Exercise 8.54 🌟
We start by establishing a new functional equation
Using Table 3.4 from the book, we get
This gives
Apply the binomial sum operation to get
Exercise 8.55
We start with the expression from Theorem 8.8
Using the standard binomial expansion, we have
Substitute this expansion back into the part of our original equation. The leading 1s cancel out, so
We want our sum to look like the one given in the book, which uses an index running from 2 to . Let (which means ). If goes from 1 to , then goes from 2 to . Substituting all of this back, and applying the "absorption" identify , gives us
Because these are finite sums for any given (and the infinite tail converges), we can safely swap the order of summation. This gives
The inner sum is a standard, converging infinite geometric series (recall that )
Substitute this collapsed fraction back into the outer sum
Exercise 8.56
We start with the recurrence for
Multiply by to avoid divisions
Let be the target EGF. It satifies the functional equation
Just like Exercise 8.54, we apply the Poisson transform by substituting . This gives
Substituting and iterating the recurrence down to zero gives the explicit infinite sum
We need to find . Letting , we extract the th coefficient for (the constant 1 drops out)
Now, apply the EGF binomial sum operation to get
To get this into a form we can approximate, we expand the denominator back into an infinite geometric series and swap the order of summation
Let's evaluate that inner sum. We start with the binomial expansion
Notice that the sum we want is exactly :
Subtract
This gives
Substitute back into our outer sum to get the exact formula for
Apply the approximation from the book
if we split the sum at , the summation over the 1s yields exactly . The remaining decaying fractional tails evaluate to a fixed constant, plus the microscopic oscillating wave. Therefore,
Exercise 8.57
We are given the recurrence for
with initial conditions and .
Let . The RHS is the standard binomial sum , whilst the LHS generates . However, we must correct for the boundary condition. Looking at the coefficients of :
LHS:
RHS:
To balance the equation, we must add to the right side. Our exact functional equation is
Now, apply the Poisson transform by multiplying the whole equation by
Substitute and iterate the equation down to 0
This gives
Now, we apply the binomial sum operation to read out
To get this into a form we can approximate, we proceed exactly as in the previous exercise. Thus,
The inner sum over is exactly for the binomial expansion , evaluated at
Substitute back in to get the exact closed form
Apply the exponential approximation from the book. We also extend the boundaries in both directions, knowing that negative indices produce exponentially small quantities.
We are summing a function evaluated at exponentially spaced points . Switching to a logarithmic scale creates equidistant points for applying the Riemann integral. In other words,
Therefore,
The microscopic oscillating term is hiding in the difference between the discrete sum over the fractional part and this continuous integral mean, exactly as we proved in the internal nodes derivation.
Exercise 8.58
The extended version of Prodinger’s algorithm is completely described in the paper The Swedish Leader Election Protocol: Analysis and Variations. In the analysis, the authors use the Poisson transform technique that’s exemplified in several previous exercises. The new algorithm introduces an additional parameter that controls the allowed number of consecutive failed (null) rounds.
Exercise 8.59
Let be the total length of the text string. The algorithm checks positions . This gives us total checkpoints.
To determine the average number of bits examined by this algorithm, we can break the problem down into two distinct scenarios: what happens at a standard checkpoint in the random text, and what happens when the algorithm hits the hidden run of zeros.
At a typical checkpoint located in the random text, the algorithm checks bits. Let be the random variable for the number of bits read in a window (initial scan). Its probability mass function is
We’ve
We know that , since after successfully reading bits, we’ll surely read one more. This gives
With probability , all bits in the window are 0. When this happens, the algorithm checks bits on the left and right to determine the run length. Because the surrounding text is random, the expected number of bits checked to the left until a 1 is found is exactly 2 (geometric distribution). The expected number to the right is also 2. This adds an expected 4 bits to our check.
The total expected number of bits examined per random checkpoint is .
There is exactly one checkpoint that falls inside the hidden run of zeros. Since the problem states that , we can safely ignore the edge case where the -bit window overlaps the boundary of the hidden run. Therefore, the bits checked will entirely consist of 0s.The algorithm will then expand to the left and the right. It will successfully read all the remaining zeros in the run, and it will only stop when it hits the 1 immediately to the left of the run and the 1 immediately to the right. Because it reads the entire hidden run plus exactly two bounding 1s, the total number of bits examined for this specific checkpoint is exactly .
Because the hidden run is uniformly distributed, the algorithm will, on average, check checkpoints before finding it. Among these 1 is a successful search and the others are failures. This gives
Exercise 8.60
The key is to adapt the skipping mechanic from the previous exercise by making the skip distance dynamic. Instead of searching for a fixed run of length , we use our "longest run found so far" to dictate how far we can safely jump ahead.
Let be the length of the longest run of 0s found so far. We initialize it to zero. The algorithm is outlined below.
Dynamic Probing
Because we only care about finding a run strictly longer than our current record , any new record-breaking run must contain at least consecutive 0s. If we are starting a search from position , we do not read bit (except when ). Instead, we skip ahead and directly probe the bit at position .
Bit is 0
If the bit at is a 0, a record-breaking run might exist here. Just like the previous exercise, we read backward toward .
If we hit a 1 while reading backward, it's a false alarm. We shift our search window past that 1 and resume probing.
If we read all the way back to and they are all 0s, we have a new record! We then read forward from to see exactly how long this new run is. At any rate, we also update to reflect this longest run of 0s as well as set our new position to continue the search after this block.
We know from the book, that in a random bitstring of length , the expected length of the longest run of zeros is roughly . By the time the algorithm is halfway through the text, will likely be close to . This is a significant improvement compared to a naive algorithm that maintains a simple counter and reads all bits of a string. This means our algorithm operates in expected time.
Last updated