ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Theory of other algorithms

The headers of include/ADS/algorithm collect the tools of the analysis of algorithms and a few algorithms that illustrate them: the solution of the recurrences of section 2.9 of the book (MasterTheorem.h, AkraBazzi.h), the amortized analysis of section 4.2 (BinaryCounter.h), the elimination of the recursion of section 4.4 (Hanoi.h), the general schemes of the techniques of design of chapters 12 to 16 (Paradigms.h), the problems on sequences solved by a scan or by a sort (MaximumSegments.h, Subsequences.h, SequenceQueries.h), and the algorithms of Monte Carlo of chapter 17 (MonteCarlo.h). This page collects what the headers take for granted: the notation of the orders of growth (see Definitions and notation), the argument behind each solution of a recurrence (see Recurrences), the two forms of the amortized analysis (see Amortized analysis), and, for each family of algorithms, the property on which its correctness rests and the argument behind its bound (from Recursion and the schemes of design to Monte Carlo algorithms). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.

Definitions and notation

The cost of an algorithm is a function \( T( n ) \) of the size \( n \) of its input, and it is compared with others by its order of growth: \( f( n ) = O( g( n ) ) \) if \( f( n ) \le c \, g( n ) \) for some \( c > 0 \) and every \( n \) large enough, \( f( n ) = \Omega( g( n ) ) \) if \( g( n ) = O( f( n ) ) \), and \( f( n ) = \Theta( g( n ) ) \) if both hold (chapter 2 of the book). The orders that the recurrences of the headers produce are all of the form

\[ c^n \, n^p \, \log^q n \, ( \log \log n )^r , \tag{1} \]

which Growth of MasterTheorem.h stores as its four exponents, with a flag for a bound that is only an upper one. Two orders (1) compare as their functions do for \( n \) large, i.e., lexicographically on \( ( c , p , q , r ) \), since each factor dominates any power of the factors after it; this gives the hierarchy \( 1 \prec \log n \prec n \prec n \log n \prec n^2 \prec 2^n \), and leaves out the orders, such as \( n^{\log n} \), that lie between two families.

The symbols of the headers of the area
SymbolMeaning
\( T( n ) \)the cost of an algorithm on an input of size \( n \), defined by a recurrence
\( a \), \( b \), \( \alpha = \log_b a \)the number of the subproblems, the factor by which each one is smaller, and the exponent that their number and size give
\( \beta \), \( k \)the exponents of the cost \( \Theta( n^\beta \log^k n ) \) of the division and of the combination
\( \Phi \)a potential, a function of the state of a structure with \( \Phi \ge \Phi_0 \)
\( D[ 0 .. n - 1 ] \), \( P[ i ] \)a sequence of numbers and its prefix sums \( P[ i ] = D[ 0 ] + \cdots + D[ i - 1 ] \), \( P[ 0 ] = 0 \), so that the segment \( D[ b .. s ] \) sums to \( P[ s + 1 ] - P[ b ] \)
\( K \)the number of independent runs of an algorithm of Monte Carlo

Recurrences

An algorithm of divide et impera that splits an instance of size \( n \) into \( a \) instances of size \( n / b \), and spends \( g( n ) = \Theta( n^\beta \log^k n ) \) to divide and to combine, costs

\[ T( n ) = a \, T( n / b ) + g( n ) . \tag{2} \]

Theorem 1 (the master theorem). With \( a \ge 1 \), \( b > 1 \) and \( \alpha = \log_b a \), the solution of (2) is \( \Theta( n^\alpha ) \) if \( \beta < \alpha \), \( \Theta( n^\beta \log^k n ) \) if \( \beta > \alpha \), and, if \( \beta = \alpha \), \( \Theta( n^\alpha \log^{k+1} n ) \) for \( k > -1 \), \( \Theta( n^\alpha \log \log n ) \) for \( k = -1 \) and \( \Theta( n^\alpha ) \) for \( k < -1 \) (Theorems 2.2 and 2.4 of the book).

Indeed, the tree of the recursion has \( \log_b n \) levels, and its level \( j \) has \( a^j \) nodes of size \( n / b^j \), which cost in all

\[ a^j \, g( n / b^j ) = \Theta\Bigl( n^\beta \bigl( a / b^\beta \bigr)^j \log^k ( n / b^j ) \Bigr) . \tag{3} \]

If \( \beta < \alpha \), then \( a / b^\beta > 1 \) and the terms (3) grow geometrically toward the leaves, whose \( a^{\log_b n} = n^\alpha \) nodes dominate; if \( \beta > \alpha \) they decrease geometrically and the root dominates. If \( \beta = \alpha \) every level costs \( n^\alpha \log^k( n / b^j ) \), and the sum over the levels is that of \( i^k \) for \( i \) from 1 to \( \log_b n \), i.e., \( \Theta( \log^{k+1} n ) \) for \( k > -1 \), the harmonic \( \Theta( \log \log n ) \) for \( k = -1 \), and a convergent series for \( k < -1 \). The floors and the ceilings of the sizes change no order. master() decides among the five cases, taking as an integer a value of \( \log_b a \) within \( 10^{-12} \) of one, so that the rounding of the logarithms does not move a recurrence from the third case to another.

When the parts have different sizes, as in \( T( n ) = T( n / 5 ) + T( 7 n / 10 ) + n \) of the selection in linear time, the theorem of Akra and Bazzi replaces \( \alpha \) by the unique real \( p \) with

\[ \sum_{i=1}^k a_i b_i^p = 1 , \qquad T( n ) = \Theta\Bigl( n^p \Bigl( 1 + \int_1^n \frac{g( u )}{u^{p+1}} \, du \Bigr) \Bigr) , \tag{4} \]

for \( T( n ) = \sum_i a_i T( b_i n ) + g( n ) \), \( a_i > 0 \), \( 0 < b_i < 1 \). The left side of the equation is strictly decreasing in \( p \), from \( + \infty \) to 0; hence its root exists and is unique, and akraBazziExponent() brackets it by doubling and halves the bracket 200 times. With \( g( n ) = \Theta( n^\beta \log^k n ) \) the integral of (4) gives the five cases of Theorem 1 with \( p \) for \( \alpha \) (akraBazzi()); in the example \( ( 1 / 5 )^p + ( 7 / 10 )^p = 1 \) has \( p < 1 = \beta \), and the selection is linear.

The recurrences that decrease the size by a constant, \( T( n ) = \sum_{i=1}^h a_i T( n - i ) + \Theta( n^\beta ) \), unfold instead into a tree of depth \( \Theta( n ) \): with \( a = \sum_i a_i = 1 \) it is a path of \( n \) nodes and the solution is \( \Theta( n^{\beta + 1} ) \), while with \( a \ge 2 \) the tree has at most \( a^n \) nodes and the solution is \( O( a^n n^\beta ) \) (Theorem 2.5, linear()). The second bound is an upper one only, since the branches of different depths make the tree smaller than a full one: the recurrence of Fibonacci, with \( a = 2 \), is \( \Theta( \phi^n ) \), \( \phi = ( 1 + \sqrt 5 ) / 2 \).

Amortized analysis

The amortized cost of an operation is its share of the total cost of any sequence of operations, which may be much less than its cost in the worst case. The binary counter of \( k \) bits (add() of BinaryCounter.h) is the example of section 4.2: an increment clears the ones at the bottom and sets the first zero, and it changes \( k \) bits when the counter is full of ones.

Lemma 2 (the binary counter). From a counter of zeros, \( n \) increments change fewer than \( 2 n \) bits.

Indeed, by aggregation, the bit \( A[ i ] \) changes once every \( 2^i \) increments, i.e., \( \lfloor n / 2^i \rfloor \) times, and

\[ \sum_{i=0}^{k-1} \Bigl\lfloor \frac{n}{2^i} \Bigr\rfloor < n \sum_{i=0}^{\infty} \frac{1}{2^i} = 2 n . \tag{5} \]

The same bound comes from the potential \( \Phi \), the number of ones of the counter, which starts at 0 and is never negative: an increment that clears \( d \) bits and sets one costs \( d + 1 \) and changes \( \Phi \) by \( 1 - d \), so that its amortized cost \( d + 1 + \Delta \Phi \) is 2, and the total cost is at most \( 2 n \) minus the final potential. The method of the potential is the one that the other structures of the library use, e.g., the Fibonacci heap and the splay tree, since it charges each operation by the state it leaves rather than by a count over the whole sequence.

Recursion and the schemes of design

A recursive procedure runs on the stack of the calls, and it can be made iterative by keeping that stack by hand (section 4.4). The towers of Hanoi (Hanoi.h) move \( n - 1 \) disks to the spare peg, the largest one to its place and the \( n - 1 \) disks over it, i.e., \( T( n ) = 2 T( n - 1 ) + 1 = 2^n - 1 \) moves, which is also a lower bound, since the largest disk moves only once the others are all on one peg. The first iterative version pushes the parameters of the first call and turns the second one, which is the last action of the procedure, into a change of the parameters (the elimination of a tail call); the second one applies the systematic rules, which save with the parameters the label from which the caller resumes, and which apply to any recursion.

The schemes of Paradigms.h write the techniques of chapters 12 to 16 once, in terms of the parts that make them concrete. A problem of search, of decision or of optimization is solved by the enumerative method when its search space \( Z \), an ordered set of objects of which the admissible ones are the solutions, can be listed (enumerateSearch(), enumerateOptimize()); backtracking (backtrack(), chapter 16) lists it as the leaves of a tree of partial solutions, and the pruning of a node that cannot lead to a solution removes its whole subtree, which is what makes it faster than the enumeration. A greedy algorithm (greedy(), chapter 14) fixes one component at each stage and never revises it, and it is correct only for the problems where an exchange argument shows that some optimum agrees with each choice (see Greedy algorithms); divide et impera (divideEtImpera(), chapter 12) costs a recurrence such as (2). With a measure that is only partially ordered the answer is the set of the maximal solutions, found by maximal() in \( O( n^2 ) \) comparisons.

Segments and subsequences

The segment of largest sum of \( D \) (chapter 2, A Warm-up, of the Pearls of Ferragina, MaximumSegments.h) is found by four algorithms that differ in what they reuse. All the pairs \( ( b , s ) \) with the sum recomputed cost \( \Theta( n^3 ) \), and with the sum extended from \( s - 1 \) to \( s \) cost \( \Theta( n^2 ) \). The linear scan rests on the following.

Lemma 3 (the scan of Kadane). An optimal segment has no prefix of negative sum; and if every prefix of \( D[ b .. s ] \) has a nonnegative sum, then for each segment that starts at some \( b' \in ( b , s ] \) the one that starts at \( b \) and ends at the same place has a sum at least as large (two properties proved in that chapter).

Indeed, removing a prefix of negative sum would increase the sum, and extending a segment that starts at \( b' \) back to \( b \) adds the prefix \( D[ b .. b' - 1 ] \), whose sum is not negative. Hence the scan of maxSumSegment() keeps the sum of the current segment, restarts it after the place where it becomes negative, and compares it with the best one at each step: \( O( n ) \) time, one pass over the array, and \( \lceil n / B \rceil \) transfers in a memory of blocks of \( B \) items, whatever \( B \). Equivalently, the best segment ending in \( s \) is \( P[ s + 1 ] - \min_{b \le s} P[ b ] \), with the minimum carried along the scan (maxSumSegmentPrefix()); with the length bounded to \( [ L , U ] \) the minimum is over a window of starts that slides to the right, which a deque of starts of increasing \( P \) gives in \( O( 1 ) \) amortized, since each start enters and leaves it once (maxSumSegmentLength()).

The longest segment of sum at least \( t \) (longestSegmentAtLeast()) walks, for each end \( i \), only the starts that could lengthen the best segment so far, of length \( \ell \): they lie left of \( i - \ell \), and among them only the leftmost minima of \( P \) count, since a start with a larger \( P \) to the right of a smaller one is worse in both respects. The chain of those minima, followed from the right, has increasing prefix sums as it moves left; the walk stops at the first start that fails, and each step past the first one lengthens the best segment by one at least. Hence the steps are at most \( 2 n \) in all. The segment of largest average with a length at least \( L \) is a question of slopes: the average of \( D[ x .. i - 1 ] \) is the slope of the segment from \( ( x , P[ x ] ) \) to \( ( i , P[ i ] ) \), and the best \( x \) is the point of tangency from \( ( i , P[ i ] ) \) to the lower convex hull of the admissible starts, kept by the monotone chain and searched by bisection (maxDensitySegment(), \( O( n \log n ) \)).

The longest increasing subsequence of Subsequences.h follows the dynamic programming of chapter 13 in \( O( n^2 ) \), with \( L[ i ] \) the longest one that ends in \( A[ i ] \), and the bound falls to \( O( n \log n ) \) by the following invariant of lisLength(): after each item,

\[ \mathit{tails}[ \ell ] = \min\{ \text{the last item of an increasing } \text{subsequence of } \ell + 1 \text{ items} \} , \tag{6} \]

a strictly increasing vector, so that the new item \( a \) extends the longest subsequence whose last item is below \( a \), found by binary search, and replaces the next entry. Finally, the questions of SequenceQueries.h reduce to a sort: the smaller items on the right of each one are counted by mergesort, since when an item of the left half is output the items of the right half already output are exactly the smaller ones on its right; and two sets of points on a line are matched at least cost in sorted order, since for \( h_1 \le h_2 \) and \( l_1 \le l_2 \) one has

\[ | h_1 - l_1 | + | h_2 - l_2 | \le | h_1 - l_2 | + | h_2 - l_1 | , \tag{7} \]

and any crossing of an optimal matching can be undone by an exchange.

Monte Carlo algorithms

An algorithm of Monte Carlo always ends within its bound, and it may answer wrongly with a probability bounded over its random choices, not over the inputs (chapter 17 of the book). The three algorithms of MonteCarlo.h have a one-sided error or an error that \( K \) runs reduce exponentially.

Lemma 4 (Schwartz and Zippel). A nonzero polynomial of total degree \( d \) in \( n \) variables vanishes at a point drawn uniformly from \( S^n \) with probability at most \( d / |S| \).

Indeed, for one variable a nonzero polynomial of degree \( d \) has at most \( d \) roots, and the general case follows by induction on \( n \), writing the polynomial as one in \( x_1 \) whose leading coefficient is a polynomial of the other variables. Hence zeroPolynomial(), with \( S = \{ 1 , \ldots , 2 d \} \) (of long points, so that \( 2 d \) must be a long, its precondition), errs with probability at most \( 1 / 2 \) per run, and only when it answers zero; \( K \) independent runs leave at most \( 2^{-K} \). The algorithm of Freivalds (freivalds(), exercise 17.4) is the same argument for the matrix \( M = A B - C \): if a row \( m \) of \( M \) is not zero, say \( m_j \ne 0 \), then for each choice of the other signs of \( x \) at most one of the two signs of \( x_j \) gives \( m \cdot x = 0 \), so that \( M x = 0 \) with probability at most \( 1 / 2 \), and each run costs three products of a matrix and a vector, \( O( n^2 ) \), against the product of two matrices. Last, halfSatisfiable() (exercise 17.5) estimates the fraction of the satisfying assignments by \( K \) samples; if it is \( 1 / 2 + \epsilon \), the bound of Hoeffding gives

\[ \Pr\Bigl[ \frac{Y}{K} \le \frac{1}{2} \Bigr] \le e^{-2 K \epsilon^2} , \tag{8} \]

\( Y \) the number of the true samples, and symmetrically below; the error is two-sided, and \( K \) must grow as \( 1 / \epsilon^2 \).

The algorithms of Monte Carlo and their errors
FunctionErrorProbability of errorTime
zeroPolynomial()one-sided, on zero\( 2^{-K} \)\( K \) evaluations
freivalds()one-sided, on equal\( 2^{-K} \)\( O( K n^2 ) \)
halfSatisfiable()two-sided\( e^{-2 K \epsilon^2} \)\( K \) evaluations

References

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, chapters 2, 4, 12 to 17, https://algoritmicamente.it/materiali/libro/capitoli/cap02.pdf
P. Ferragina, Pearls of Algorithm Engineering, Cambridge University Press, 2023, chapter 2 (A Warm-up), doi:10.1017/9781009128933
M. Akra, L. Bazzi, On the solution of linear recurrence equations, Computational Optimization and Applications 10(2), 195-210, 1998, doi:10.1023/A:1018373005182
T. Leighton, Notes on better master theorems for divide-and-conquer recurrences, MIT, 1996
J. Bentley, Programming pearls: algorithm design techniques, Communications of the ACM 27(9), 865-873, 1984, doi:10.1145/358234.381162
Y.-L. Lin, T. Jiang, K.-M. Chao, Efficient algorithms for locating the length-constrained heaviest segments with applications to biomolecular sequence analysis, Journal of Computer and System Sciences 65(3), 570-586, 2002, doi:10.1016/S0022-0000(02)00010-7
M. H. Goldwasser, M.-Y. Kao, H.-I. Lu, Linear-time algorithms for computing maximum-density sequence segments with bioinformatics applications, Journal of Computer and System Sciences 70(2), 128-144, 2005, doi:10.1016/j.jcss.2004.08.001
M. L. Fredman, On computing the length of longest increasing subsequences, Discrete Mathematics 11(1), 29-35, 1975, doi:10.1016/0012-365X(75)90103-X
J. T. Schwartz, Fast probabilistic algorithms for verification of polynomial identities, Journal of the ACM 27(4), 701-717, 1980, doi:10.1145/322217.322225
R. Zippel, Probabilistic algorithms for sparse polynomials, EUROSAM 1979, LNCS 72, 216-226, 1979, doi:10.1007/3-540-09519-5_73
R. Freivalds, Probabilistic machines can use less running time, IFIP Congress 1977, 839-842
W. Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301), 13-30, 1963, doi:10.1080/01621459.1963.10500830