|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/sequence realize the SEQUENCE of section 3.2.1 of the book and the LIST of chapter 4, i.e., a vector that doubles and halves (section 4.2), the bidirectional circular list with a sentinel (section 4.1), the singly linked list of exercise 4.6, the lists with cursors in one vector, and, beyond the book, a vector with room for a few items inside itself and the tiered vector of Goodrich and Kloss; next to them are the algorithms that work on a sequence through its positions (the searches, the natural merge sort, the merge) or on a vector in place (the partition into three classes and a few other rearrangements). This page collects the definitions and the notation that the headers share (see Definitions and notation), the realizations with the costs of their operations (see Realizations and their costs), the amortized analysis of the vectors that change their size (see Vectors that change their size), and, for the algorithms, the property on which each is correct and the argument behind its bound (see Searching, merging and sorting a sequence and Rearrangements in place), and the lists by rank of chapters 2 and 3 of Morin's Open Data Structures with the answers to their exercises (see Lists by rank (Morin's book)), and the sequences by rank on skip lists and treaps and the order maintenance of his chapters 4, 7 and 8 (see Sequences by rank and order maintenance), and the array that tells its changes with the prefix aggregates of Fenwick that it feeds (see Prefix aggregates of an observable array). The pseudocode of each operation and of each algorithm is 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.
A sequence \( s = s_0 , s_1 , \ldots , s_{n-1} \) is a finite list of \( n \ge 0 \) items, possibly repeated, in which the order matters; the SEQUENCE of the book (see Abstract data types and their axioms, and the concept Sequence of ADT.h) reaches its items through positions, values of a type Pos that the realization chooses, rather than through indices. The position \( \mathit{pos}_i \) leads to \( s_i \) for \( 0 \le i < n \), and two more positions, \( \mathit{pos}_{-1} \) and \( \mathit{pos}_n \), stand before the first item and after the last one, so that a scan reads
\[ p \gets \mathrm{head}();\ \textbf{while not}\ \mathrm{finished}( p ) \ \textbf{do}\ \ldots\ \mathrm{read}( p ) \ldots ;\ p \gets \mathrm{next}( p ) . \tag{1} \]
What a position is decides the cost of each operation: an index costs nothing to move along but makes an insertion shift the items after it, while a pointer to a cell makes an insertion change two links but gives no access by index. A run of a sequence is a maximal stretch of consecutive items in nondecreasing order, and a sequence of \( r \) runs has \( r - 1 \) descents, i.e., places with \( s_{i+1} < s_i \).
| Symbol | Meaning |
|---|---|
| \( n \), \( s_i \) | the number of items, and the item of index \( i \), \( 0 \le i < n \) |
| \( \mathit{pos}_i \) | the position of \( s_i \), and \( \mathit{pos}_{-1} \), \( \mathit{pos}_n \) those before the first item and after the last one, on which finished() is true |
| \( c \) | the capacity of a vector, the number of items it has room for |
| \( \alpha = n / c \) | the load of a vector |
| \( \Phi \) | a potential, a function of the state of a structure that pays for its dear operations |
| \( b \) | the number of places of a block of the tiered vector, a power of 2 |
| \( r \) | the number of runs of a sequence |
| \( A[ 0 .. n - 1 ] \) | a vector of the C++ code, indexed from 0, and \( A[ i .. j ) \) its places from \( i \) to \( j - 1 \) |
The library has six realizations of a sequence, four of which have the positions of the book and model Sequence, while the other two are vectors with access by index only.
| Realization | Position | Space | read(), next() | prev(), tail() | insert(), remove() | access by index |
|---|---|---|---|---|---|---|
| ArraySequence | the index | \( \Theta( n ) \) | \( O( 1 ) \) | \( O( 1 ) \) | \( O( n - i ) \), \( O( 1 ) \) amortized at the end | \( O( 1 ) \) |
| List | the cell of the item | \( \Theta( n ) \) | \( O( 1 ) \) | \( O( 1 ) \) | \( O( 1 ) \) | \( O( i ) \) by a scan |
| SinglyList | the cell before the item | \( \Theta( n ) \) | \( O( 1 ) \) | \( O( n ) \) | \( O( 1 ) \) | \( O( i ) \) by a scan |
| CursorList | the cursor of the cell before the item | \( \Theta( n ) \), shared by the lists of a space | \( O( 1 ) \) | \( O( n ) \) | \( O( 1 ) \) amortized | \( O( i ) \) by a scan |
| SmallVector | none | \( O( n + N ) \) | none | none | \( O( 1 ) \) amortized at the end | \( O( 1 ) \) |
| TieredVector | none | \( n + O( \sqrt{n} ) \) | none | none | \( O( \sqrt{n} ) \) amortized anywhere | \( O( 1 ) \) |
| SkipListSequence, TreapList | none | \( \Theta( n ) \) expected | none | none | \( O( \log n ) \) expected anywhere | \( O( \log n ) \) expected |
An insertion in a vector at the index \( i \) moves the \( n - i \) items after it one place on, and a removal moves them back; hence the vector is preferable when the sequence is mostly read, by index or in order, and changed at its end, and its items are contiguous, which makes a scan read the memory forward. A list changes in \( O( 1 ) \) time at any position it holds, since an insertion allocates a cell and changes the links of its two neighbors, but it has no access by index, and a scan follows pointers that may be scattered in memory; the cells of List and of SinglyList come therefore from a pool, so that the cells made one after another are next to each other.
Lemma 1 (the position before the item). In a list whose cells have a link to the next one only, an insertion before \( s_i \) and the removal of \( s_i \) change the link of the cell of \( s_{i-1} \) (or the link to the first cell, for \( i = 0 \)); with \( \mathit{pos}_i \) the cell of \( s_{i-1} \), and nil for \( i = 0 \), both take \( O( 1 ) \) time, while prev() and tail() take \( \Theta( n ) \) in the worst case.
Indeed, the link to change is the one that points to the cell of \( s_i \), which is in the cell before it, and no link leads from a cell back to its predecessor; a position that held the cell of \( s_i \) itself would force a scan from the head to find it, i.e., \( \Theta( i ) \) time. With the position before the item, the scan is needed only to go backwards, i.e., by prev() and by tail(), which is the convention of the realizations with pointers and with cursors of Aho, Hopcroft and Ullman. SinglyList and CursorList follow it, with \( \mathit{pos}_n \) the last cell; after insert( p , v ) the new item has the position \( p \), and after remove( p ) its successor has it. The bidirectional list List keeps instead both links in each cell and a sentinel, a cell with no item that is the predecessor of the first cell and the successor of the last one: every cell has then both neighbors, and the insertion and the removal have no special case for the empty list or for the ends, the sentinel being \( \mathit{pos}_{-1} \) and \( \mathit{pos}_n \) at once.
A list with cursors (CursorList) keeps its cells in a vector, shared by several lists, the link of a cell being the index of the next one and 0 being nil; the free cells form one more list in the same vector, the free list, from which take() removes its first cell and to which give() returns a cell, each in \( O( 1 ) \) time. When the free list is empty the vector doubles, which costs \( O( 1 ) \) amortized by Lemma 2 below, and the cursors stay valid, since an index does not change when the vector is moved, while a pointer would.
A vector of capacity \( c \) holds \( n \le c \) items; when an insertion finds it full it is replaced by one of capacity \( 2 c \), and the \( n \) items are moved there, which costs \( \Theta( n ) \). The cost of a single insertion is therefore \( \Theta( n ) \) in the worst case, but that of a sequence of operations is linear in their number.
Lemma 2 (the doubling, section 4.2.1). Starting from the empty vector, \( n \) insertions at the end cost in all
\[ C( n ) = \sum_{i=1}^n c_i \le n + \sum_{k=0}^{\lfloor \log_2 n \rfloor} 2^k \le n + 2^{\lfloor \log_2 n \rfloor + 1} - 1 \le 3 n , \tag{2} \]
with \( c_i = i \) when the \( i \)-th insertion finds the vector full, i.e., when \( i - 1 \) is a power of 2, and \( c_i = 1 \) otherwise.
The bound (2) is the sum of the moves of the doublings, each a power of 2 up to \( n \), and of one write per insertion; hence an insertion at the end costs \( O( 1 ) \) amortized. Growing the vector by a constant \( d \) instead of doubling it gives a resize every \( d \) insertions, the \( k \)-th one moving \( k d \) items, i.e., \( \Theta( n^2 / d ) \) in all, which is quadratic.
A vector that only grows keeps the space of its largest size. To keep the space \( O( n ) \), ArraySequence halves its capacity when a removal leaves it with \( n \le c / 4 \) items (halving it at \( n = c / 2 \) would make an insertion and a removal around that size each cost \( \Theta( n ) \), a resize every time).
Lemma 3 (the doubling and the halving). Any sequence of insertions and removals at the end of a vector that doubles when it is full and halves when it is a quarter full costs \( O( 1 ) \) amortized time per operation.
Indeed, let the potential be
\[ \Phi = \begin{cases} 2 n - c & \text{if } \alpha \ge 1 / 2 , \cr c / 2 - n & \text{if } \alpha < 1 / 2 , \end{cases} \tag{3} \]
which is never negative and is 0 when the vector is half full. An operation that does not resize changes \( n \) by 1 and \( \Phi \) by at most 2, i.e., its amortized cost, its cost plus the change of \( \Phi \), is at most 3. A doubling happens at \( n = c \), where \( \Phi = n \), and a halving at \( n = c / 4 \), where \( \Phi = c / 4 = n \): in both cases the \( n \) moves are paid by the potential, which falls to \( O( 1 ) \) (Cormen, Leiserson, Rivest and Stein, section 17.4, after Tarjan). CursorSpace grows in the same way, and SmallVector doubles once its \( N \) inner places are full, so that \( n \) insertions move fewer than \( 2 n \) items and the space is at most \( 2 n + N \) items; with ADS_WITH_BOOST defined it runs on boost::container::small_vector with the growth factor 2, so that the same bounds hold.
The tiered vector of Goodrich and Kloss trades the access in \( O( 1 ) \) of a vector for an insertion and a removal at any index in \( O( \sqrt{n} ) \). Its items are in blocks of \( b \) places, each a circular buffer with the offset of its first item, all full but the last one; the item of index \( i \) is the item \( i \bmod b \) of the block \( \lfloor i / b \rfloor \), i.e., with \( b \) a power of 2, a shift and a mask, and inside the block it is at the place \( ( \mathit{off} + i ) \bmod b \).
Lemma 4 (the tiered vector). An insertion or a removal at the index \( i \) moves \( O( b + n / b ) \) items, i.e., \( O( \sqrt{n} ) \) with \( b = \Theta( \sqrt{n} ) \), and keeping \( b \) the least power of 2 not below \( \sqrt{n} \), by a rebuild in \( O( n ) \) when \( n \) leaves \( [ b^2 / 4 , 4 b^2 ] \), costs \( O( 1 ) \) amortized per operation.
Indeed, an insertion moves by one place the items of its block after \( i \), fewer than \( b \), and then, from the last block back to the block after that of \( i \), the last item of each block to the front of the next one; the front of a circular buffer moves by decreasing its offset, i.e., in \( O( 1 ) \), and there are at most \( n / b + 1 \) blocks. A removal does the converse. Right after a rebuild \( b \) is the least power of 2 with \( b^2 \ge n \), i.e., \( b^2 / 4 < n \le b^2 \), and the rebuilds that \( n \) crossing a bound triggers leave \( n \) about \( b^2 \) for the new \( b \); the next rebuild needs \( n \) to grow to \( 4 b^2 \) or to fall to \( b^2 / 4 \), i.e., \( \Omega( n ) \) operations, which pay for its \( O( n ) \) moves. The space is that of the \( n \) items and of at most one block not full, i.e., \( n + O( \sqrt{n} ) \).
The algorithms of SequenceAlgorithms.h use only the operations of the SEQUENCE, so that they run on every realization, with the cost of a scan (1), i.e., \( \Theta( n ) \) calls of next() and read(). A search for an item compares it with the items in order, \( n \) comparisons when it misses; on a sorted sequence it may stop at the first larger item, but the comparisons stay \( \Theta( n ) \) in the worst case, since the positions give no access in the middle (the binary search of the vectors needs the access by index). The merge of two sorted sequences of lengths \( n_1 \) and \( n_2 \) appends at each step the smaller of their first items not yet taken, the one of the first sequence among equals, i.e., it is stable and makes at most \( n_1 + n_2 - 1 \) comparisons.
Lemma 5 (the natural merge sort). A pass that distributes the runs of a sequence alternately to two sequences and merges them in pairs leaves at most \( \lceil r / 2 \rceil \) runs; hence the sort of a sequence of \( r \) runs makes \( \lceil \log_2 r \rceil \) passes and costs \( O( n \log r ) \), i.e., \( O( n \log n ) \) in the worst case and \( \Theta( n ) \) on a sorted sequence, which one scan finds to be a single run.
Indeed, the merge of two sorted runs is a sorted stretch, and two runs that go to the same sequence one after another may only join into one; the \( j \)-th pair of the merge therefore covers the runs \( 2 j - 1 \) and \( 2 j \) of the pass, and gives one run or part of one. Each pass costs \( \Theta( n ) \) reads and writes. The bound adapts to the order already present, as \( \log r \) falls from \( \log n \) to 0. It is also optimal up to a constant factor in the worst case for a given \( r \): the permutations whose runs have the lengths \( \ell_1 , \ldots , \ell_r \) are at most \( n! / ( \ell_1! \cdots \ell_r! ) \), whose logarithm is at most \( n \log_2 r \) and is \( \Omega( n \log r ) \) when the runs are of equal lengths, and a sort by comparisons must tell them apart (McIlroy). The bubble sort, instead, swaps adjacent items out of order until a pass has no swap; each swap removes one inversion, and the passes are at most \( n \), i.e., \( O( n^2 ) \) comparisons and swaps.
listSort() of ListSort.h sorts a List by relinking its cells, so that no item is copied and the positions stay on their items. It cuts the list into its runs, reversing those strictly decreasing (strictly, so that the sort stays stable), and merges them as a binary counter: the place \( k \) of an array holds the merge of \( 2^k \) runs or nothing, and a new run is merged with the places \( 0 , 1 , \ldots \) while they are full, as a carry propagates. Each run takes part in at most \( \lceil \log_2 r \rceil + 1 \) merges, which gives \( O( n \log r ) \) comparisons and \( n - 1 \) on a sorted or a reversed list, in \( O( 1 ) \) space beyond the array of 64 places. On the numbers in their natural order it uses instead the radix sort on the pairs (key, cell), in \( O( n ) \) time and space, since a merge sort walks the scattered cells \( \log r \) times and misses the cache at each of them.
The functions of Rearrangements.h reorder a vector \( A[ 0 .. n - 1 ] \) by swaps, or with a buffer much smaller than \( n \).
Lemma 6 (the Dutch national flag, Dijkstra). With the indices \( i \le j \le k \), the invariant
\[ A[ 0 .. i ) \text{ of color 0} , \quad A[ i .. j ) \text{ of color 1} , \quad A[ j .. k ) \text{ not examined} , \quad A[ k .. n ) \text{ of color 2} \tag{4} \]
holds at the start with \( i = j = 0 \) and \( k = n \) and is kept by a step that examines \( A[ j ] \); hence the items are partitioned by color after \( n \) steps, with \( n \) reads of a color and at most \( n \) swaps.
Indeed, an item of color 0 is swapped with \( A[ i ] \), which is of color 1 (or is \( A[ j ] \) itself), and both \( i \) and \( j \) grow; one of color 1 makes \( j \) grow; one of color 2 is swapped with \( A[ k - 1 ] \), not examined yet, and \( k \) falls. Each step makes the stretch not examined one shorter, and swaps at most once. It is the partition of the quicksort with three ways, the keys smaller than, equal to and larger than the pivot being the three colors.
The alternating order \( A[ 0 ] \le A[ 1 ] \ge A[ 2 ] \le A[ 3 ] \ge \cdots \) takes one pass of \( n - 1 \) comparisons (wiggleSort()): if \( A[ 0 .. i ] \) alternates and \( A[ i ] \) and \( A[ i + 1 ] \) are in the wrong order, their swap keeps the order of \( A[ i - 1 ] \) and \( A[ i ] \), by transitivity (e.g., for an odd \( i \) with \( A[ i - 1 ] \le A[ i ] < A[ i + 1 ] \), the swap puts at the place \( i \) the larger \( A[ i + 1 ] \), which is still at least \( A[ i - 1 ] \)).
A vector is \( k \)-sorted when each item is at most \( k \) places away from its place in the sorted order; then the item of the place \( i \) of the sorted order is the least of those left among \( A[ i .. i + k ] \), and sortKSorted() keeps them in a heap of \( k + 1 \) items, which gives each item in \( O( \log k ) \), i.e., \( O( n \log k ) \) in all against the \( O( n k ) \) of the insertion sort. No sort by comparisons does better: the \( k \)-sorted orders of \( n \) items are at least \( ( k! )^{n / k} \) (the blocks of \( k \) places permuted independently), and a decision tree with that many leaves has a height of at least \( \log_2 ( k! )^{n / k} = \Omega( n \log k ) \).
Finally, the permutation that sorts distinct items splits into cycles, and a swap that puts one item in its place shortens its cycle by one; a cycle of \( k > 1 \) items needs therefore \( k - 1 \) swaps, and the fewest swaps that sort the vector are \( n \) minus the number of cycles (minimumSwapSort()). When a swap costs the sum of its two items, a cycle of \( k \) items of sum \( s \) and least item \( m \) is sorted at the least cost
\[ \min\{ s + ( k - 2 ) m , \ s + m + ( k + 1 ) M \} , \tag{5} \]
\( M \) the least item of the vector: either \( m \) is swapped in turn with each other item of the cycle, which takes part in one swap while \( m \) takes part in \( k - 1 \), or \( M \) enters the cycle by a swap with \( m \), does the same \( k - 1 \) swaps, and is swapped back (Knuth, section 1.3.3, on the cycles of a permutation). When no item is negative, the sum of (5) over the cycles is the least cost of all the sorts by swaps: written as \( s - m + \min\{ ( k - 1 ) m , 2 m + ( k + 1 ) M \} \), which is 0 on a cycle of one item, it falls by at most \( x + y \) at a swap of \( x \) and \( y \), whether the swap joins two cycles or splits one; with two items of negative sum no least cost exists.
The interface LIST of chapter 1 of Morin's book reaches the items by their rank, \( \mathrm{get}( i ) \), \( \mathrm{set}( i , x ) \), \( \mathrm{add}( i , x ) \) and \( \mathrm{remove}( i ) \) for \( 0 \le i < n \) (\( i \le n \) for \( \mathrm{add} \)), rather than by positions; the concept IndexedList of IndexedList.h states it with the names of the standard library (operator[], insert( i , x ), erase( i )), and IndexedDeque states the DEQUE, the sequence changed at its two ends. The table gives the realizations of chapters 2 and 3 of Morin and of their exercises; \( \mu = \min\{ i , n - i \} \) is the distance of the rank from the nearer end.
| Realization | Morin | operator[] | insert(), erase() | space beyond \( n \) items |
|---|---|---|---|---|
| ArraySequence | ArrayStack, FastArrayStack (2.1, 2.2) | \( O( 1 ) \) | \( O( 1 + n - i ) \) | \( \le 3 n \) places |
| RingDeque | ArrayQueue, ArrayDeque (2.3, 2.4) | \( O( 1 ) \) | \( O( 1 + \mu ) \) | \( < n \) places, until shrink_to_fit() |
| DualArrayDeque | DualArrayDeque (2.5) | \( O( 1 ) \) | \( O( 1 + \mu ) \) | those of its two stacks |
| RootishArrayStack | RootishArrayStack (2.6) | \( O( 1 ) \) | \( O( 1 + n - i ) \) | \( O( \sqrt{n} ) \) |
| DualArrayDeque on RootishArrayStack | exercise 2.9 | \( O( 1 ) \) | \( O( 1 + \mu ) \) | \( O( \sqrt{n} ) \) |
| Treque | exercise 2.3 | \( O( 1 ) \) | \( O( 1 + \min\{ \mu , | n / 2 - i | \} ) \) | those of two RingDeque |
| ContiguousDeque | exercise 2.8 | \( O( 1 ) \) | \( O( 1 + \mu ) \) | \( \le 8 n + 24 \) places |
| TieredVector | exercises 2.10, 2.11 | \( O( 1 ) \) | \( O( 1 + \min\{ \mu , \sqrt{n} \} ) \) | \( O( \sqrt{n} ) \) |
| CubishArrayStack | exercise 2.12 | \( O( 1 ) \) | \( O( n^{1/3} ) \) | \( O( n^{2/3} ) \) |
| SinglyList | SLList (3.1) | \( O( 1 + i ) \) | \( O( 1 + i ) \) | \( n \) pointers |
| List | DLList (3.2) | \( O( 1 + \mu ) \) | \( O( 1 + \mu ) \) | \( 2 n \) pointers |
| SEList | SEList (3.3), exercises 3.17, 3.18 | \( O( 1 + \mu / b ) \) | \( O( b + \mu / b ) \) | \( O( b + n / b ) \) |
| XorList | section 3.4 | none | \( O( 1 ) \) at the ends | \( n \) words |
The rest of this section gives the argument behind each bound that is not the one of a shift of \( n - i \) items, and, for the exercises of the three chapters that ask for a proof or a discussion, the answer.
ArraySequence is the ArrayStack of Morin: Lemma 2 above is the lemma of his section 2.1.2, with the halving at a quarter where Morin halves at a third, which changes the constant only. Exercise 2.1 of the Java edition of the book asks where the extra item of the array is after a removal: in the place \( n \), the item that the shift moved out of it, which in C++ is the husk left by a move, alive until an insertion or a resize overwrites it; it keeps its resources only if its move does not take them (a std::string or a std::vector gives them away). Exercise 2.1 asks for addAll( i , c ): \( k \) calls of \( \mathrm{add}( i , x ) \) move the \( n - i \) items after \( i \) \( k \) times, \( \Theta( k ( n - i ) ) \), while one shift by \( k \) places after one resize moves them once, \( O( n - i + k ) \) (the range insert() of ArraySequence).
RingDeque is the ArrayQueue and the ArrayDeque of Morin: the items in consecutive places of a circular vector, an insertion at the rank \( i \) moving the \( \min\{ i , n - i \} \) items of the shorter side by one place. The capacity is a power of 2, so that the place of the rank \( i \) is \( ( h + i ) \mathbin{\&} ( m - 1 ) \) (exercise 2.7: the bitwise and in place of a division), and the shifts move the runs of items contiguous in the vector, three at most, by std::move(), i.e., by memmove() for the items trivially copyable (exercise 2.6, the System.arraycopy() of the Java edition). rotate( r ) moves \( \min\{ r , n - r \} \) items from one end to the other, and none when the vector is full, where moving the head is enough (exercise 2.5).
Lemma 7 (the balance of two stacks, section 2.5.1 of Morin). Let the DualArrayDeque hold its \( n \) items in two stacks \( F \) and \( B \), and deal them again into \( \lfloor n / 2 \rfloor \) and \( \lceil n / 2 \rceil \) items whenever \( 3 |F| < |B| \) or \( 3 |B| < |F| \). Then \( m \ge 1 \) operations from the empty deque spend \( O( m ) \) time in the balances, and an operation at the rank \( i \) shifts \( O( 1 + \min\{ i , n - i \} ) \) items.
Indeed, after a balance of \( n \) items the two stacks differ by one item at most, and an operation changes \( |F| - |B| \) by one, while the next balance needs \( \max \ge 3 \min \), i.e., \( | |F| - |B| | \ge ( n' - 2 ) / 2 \) for its \( n' \) items: at least \( n' / 2 - 2 \) operations, which pay for its \( O( n' ) \). An operation at the rank \( i < |F| \) shifts the \( i \) items above it in \( F \), and one at \( i \ge |F| \) the \( n - i \) items above it in \( B \); before it the stacks are balanced (or \( n < 2 \)), so that \( |F| \le 3 |B| \) gives \( |F| \le 3 n / 4 \), hence \( i < 3 n / 4 \) and \( i < 3 ( n - i ) \), i.e., \( i \le 3 \min\{ i , n - i \} \), and the same for \( B \).
The Treque of exercise 2.3 splits the items in the middle instead, into two circular deques \( L \) and \( R \) whose sizes differ by one at most, kept so by one item moved from the back of one to the front of the other after each operation: an operation at \( i < |L| \) shifts \( \min\{ i , |L| - i \} \) items, i.e., \( \min\{ i , n / 2 - i \} \) up to a constant, and one at \( i \ge |L| \) shifts \( \min\{ i - n / 2 , n - i \} \), together \( O( 1 + \min\{ i , n - i , | n / 2 - i | \} ) \) with no amortization but that of the doublings.
The ContiguousDeque of exercise 2.8 keeps the items in one contiguous piece \( A[ h .. h + n - 1 ] \) of a vector of \( c \) places, with no modular arithmetic; when an operation needs a place beyond an end, the items are put in the middle of \( 3 n + 8 \) places, at least \( n + 4 \) free on each side, so that at least \( n + 4 \) operations come before the next rebuild, which pays its \( O( n ) \) (the hint of the exercise asks for \( n / 2 \)). A rebuild after a removal that leaves more than \( 9 n + 24 \) places keeps the space linear, and a rebuild in the same vector, by memmove(), costs no allocation when the vector is already of the right size, the common case of a queue that runs along it.
The RootishArrayStack of Brodnik, Carlsson, Demaine, Munro and Sedgewick keeps its items in \( r \) blocks of \( 1 , \ldots , r \) places, the rank \( i \) in the block
\[ b( i ) = \Bigl\lceil \frac{ -3 + \sqrt{ 9 + 8 i } }{ 2 } \Bigr\rceil \; , \tag{6} \]
the least \( b \) with \( ( b + 1 ) ( b + 2 ) / 2 > i \), at the place \( i - b ( b + 1 ) / 2 \) of it.
Lemma 8 (the space of the rootish array, section 2.6.2 of Morin). A RootishArrayStack that adds a block when its \( r ( r + 1 ) / 2 \) places are full and frees the last one while \( ( r - 2 ) ( r - 1 ) / 2 \ge n \) has \( ( r - 2 ) ( r - 1 ) / 2 < n \le r ( r + 1 ) / 2 \), hence \( r \le \sqrt{ 2 n } + 2 \) and at most \( 2 r - 1 \le \sqrt{ 8 n } + 3 \) places unused; no array of \( n \) items that grows and shrinks by one item in \( O( 1 ) \) time can waste \( o( \sqrt{n} ) \) places.
Indeed, the places of the blocks are \( r ( r + 1 ) / 2 \) and \( n > ( r - 2 ) ( r - 1 ) / 2 \), whose difference is \( 2 r - 1 \); the lower bound is that of Brodnik et al., who show that after the insertion of \( n \) items some sequence of operations must leave \( \Omega( \sqrt{n} ) \) places wasted or allocated and not yet used. The blocks added and freed cost \( O( 1 ) \) amortized, as in Lemma 2, since one block of \( r \) places is added or freed after \( r - 1 \) operations at least. The test ods-2.6.rootish-array-stack checks the bound \( 2 r + 1 \) (the block kept for the next insertions included) after every operation of \( 10^5 \) insertions and removals.
Section 2.6.4 of Morin computes (6) with no floating point, by a table of the square roots of the integers below \( 2^{16} \) and a table of the logarithms; RootishArrayStack::block() takes the square root of a double, exact on the integers below \( 2^{52} \), and corrects the result by the two comparisons with \( b ( b + 1 ) / 2 \) and \( ( b + 1 ) ( b + 2 ) / 2 \), which also absorb the rounding of the root (Morin's code computes \( 9 + 8 i \) in an int, which overflows for \( i > 2^{28} \)). The tables cost two reads that may miss the cache, the root of a double a latency of about 15 to 20 cycles on the current processors, and the choice is left to the benchmarks.
A DualArrayDeque whose two stacks are RootishArrayStack (exercise 2.9) wastes \( O( \sqrt{n} ) \) places in each stack, and shifts \( O( 1 + \min\{ i , n - i \} ) \) items by Lemma 7. Its balance is done in place, for either kind of stack: the larger stack \( G \) gives its \( t = \bigl| |F| - \lfloor n / 2 \rfloor \bigr| \le \lceil n / 2 \rceil \) bottom items (fewer than \( n / 2 \) unless the other is empty) to the bottom of the other one \( S \), which grows by \( t \) places and moves its items \( t \) places up from its top down, so that no item is overwritten before it is read; then \( G \) moves its other items \( t \) places down and gives back its \( t \) top places. Each item moves once, \( n \) moves in all, and the peak is the places of \( n + t \le \lceil 3 n / 2 \rceil \) items, plus the \( O( \sqrt{n} ) \) of the blocks of the two RootishArrayStack, where building two new stacks held the places of \( 2 n \) items. The peak cannot drop to \( n + O( \sqrt{n} ) \) by moving the \( t \) items in rounds: a round of \( k \) items shifts both stacks, \( \Theta( n ) \) moves, and \( t / k \) rounds cost \( \Theta( n t / k ) \), i.e., \( \Theta( n \sqrt{n} ) \) for \( k = \sqrt{n} \), against the \( O( n ) \) that the analysis of Lemma 7 allows.
Neither the balance nor the rebuild of ContiguousDeque is spread over the operations, i.e., de-amortized, for two reasons. First, the bound that matters for a LIST by rank, \( O( 1 + \min\{ i , n - i \} ) \), is amortized anyway on these structures, whose insertion in the middle shifts \( \Theta( n ) \) items; a balance or a rebuild spread over the operations would only make the operations at the two ends \( O( 1 ) \) in the worst case. Second, the global rebuilding that would do it (that of RealTimeMinDeque, see The minimum in constant worst-case time) keeps the old representation in use while the new one is filled, and so needs copies of the items, not moves (the old cells stay readable through operator[], and for ContiguousDeque through data() and the iterators, which are pointers into the one contiguous piece); two representations at once, i.e., the places of \( 2 n \) items or more, which is what the balance in place above avoids; every insertion and removal in the middle replayed on the part already copied; and the old cells destroyed a few at a time afterwards. The constant work per operation at the ends would then be several times that of the amortized structure, whose rebuild of ContiguousDeque is moreover one memmove() in place for the items trivially copyable; a deque that needs \( O( 1 ) \) in the worst case at the ends is the linked Dequeue, which allocates one cell per insertion.
Lemma 9 (the tiered vector with a gap, exercises 2.10 and 2.11). Let a TieredVector keep its items in blocks of \( b \) places, \( b^2 / 4 \le n \le 4 b^2 \), all full but the first, with \( g < b \) places free at its front, and the last; let an insertion or a removal at the rank \( i \) shift toward the back when \( i \ge n / 2 \) and toward the front otherwise. Then it moves
\[ O\bigl( 1 + \min\{ \mu , b \} + \mu / b \bigr) = O\bigl( 1 + \min\{ i , \sqrt{n} , n - i \} \bigr) \tag{7} \]
items, \( \mu = \min\{ i , n - i \} \), plus \( O( 1 ) \) amortized for the blocks added and removed and for the rebuilds when \( b \) changes, and wastes \( O( \sqrt{n} ) \) places.
Indeed, a shift toward the back moves the items of the block of \( i \) after \( i \), at most \( \min\{ b , n - i \} \), and then one item between each two consecutive blocks after it, at most \( ( n - i ) / b + 1 \) of them, in \( O( 1 ) \) each since a block is circular; the shift toward the front is the mirror, the gap of the first block playing the part of the free places of the last one, so that \( \min\{ b , i \} + i / b + 1 \) items move. A block is added at the front only when the gap is 0, after which \( b \) insertions at the front come before the next one, and inserting the pointer to it in front of the \( n / b \) others costs \( O( n / b ) = O( b ) \), i.e., \( O( 1 ) \) amortized. The bound of exercise 2.10, \( O( 1 + \min\{ \sqrt{n} , n - i \} ) \), is (7) without the shifts toward the front.
Lemma 10 (the cubish array, exercise 2.12). Let CubishArrayStack keep its items in leaves of \( b \) places, \( b^3 / 8 \le n \le 8 b^3 \), gathered into middle blocks of \( b^2 \) items, all full but the last, each middle block being a circular sequence of leaves all full but the first (with a gap) and the last. Then operator[] takes \( O( 1 ) \) time, an insertion or a removal \( O( n^{1/3} ) \) amortized time, and the places wasted are \( O( n^{2/3} ) \).
Indeed, a middle block pushes an item at its front and pops one from its back in \( O( 1 ) \) time, by its gap and the offset of its last leaf, as the first and the last block of Lemma 9 do; an insertion moves the last item of each full middle block after the one of \( i \) to the front of the next one, \( O( n / b^2 + 1 ) = O( b ) \) of them, and inserts in its middle block as a tiered vector of \( b \) leaves does, \( O( b ) \) by Lemma 9. Each middle block wastes the free places of its first and its last leaf and has a directory of \( 2 b \) leaves, \( O( b ) \) for each of \( O( n / b^2 + 1 ) \) middle blocks, i.e., \( O( n / b ) = O( n^{2/3} ) \); the rebuilds, when \( n \) leaves \( [ b^3 / 8 , 8 b^3 ] \), cost \( O( n ) \) once every \( \Omega( n ) \) operations. This is the tiered vector of Goodrich and Kloss with three levels; the deque of middle blocks makes the two operations at the ends of a middle block cost \( O( 1 ) \), which the cascade of an insertion needs.
SinglyList is the SLList of Morin: it keeps its last cell and its size, so that it is a stack at its front and a queue from its back to its front in \( O( 1 ) \) time. A dummy cell before the first one cannot remove the special cases of these operations (exercise 3.1): the queue removes at the front and adds at the back, and the back is the last cell, which must be set apart from the dummy when the list is empty, while a removal at the back would need the cell before the last one, which a singly linked list reaches only by a scan. secondLast() (exercise 3.2) stops at the cell whose successor has no successor, with no use of the size; the operations by rank of exercise 3.3 walk \( i \) cells; reverse() (exercise 3.4) turns each link back while it walks, three pointers and no cell made; checkSize() (exercise 3.5) counts the cells.
List is the DLList of Morin: a cell of rank \( i \) is reached from the sentinel by the nearer end, \( \min\{ i , n - i \} \) links (position(), Morin's getNode()). rotate( r ) (exercise 3.8) moves the sentinel before the cell of rank \( n - r \), so that this cell is the first one, in \( O( 1 + \min\{ r , n - r \} ) \) and with no item moved; truncate( i ) (exercise 3.9) cuts the chain before the cell of rank \( i \) and hangs it on the sentinel of a new list, in \( O( 1 + \min\{ i , n - i \} ) \); absorb() (exercise 3.10) links the chain of the other list after the last cell, in \( O( 1 ) \); deal() (exercise 3.11) relinks every second cell into a new list; reverse() (exercise 3.12) exchanges the two links of each cell and of the sentinel. These operations move cells between lists, which a list of cells from new does as Morin's does; the cells of a pooled list belong to its pool [see ObjectPool.h], so that truncate(), deal() and takeFirst() move the items into cells of the other list, while absorb() takes the pool of the other list together with its cells (ObjectPool::adopt(), which walks the \( O( \log n ) \) blocks of a pool).
Lemma 11 (the merge sort of a list, exercise 3.13). The merge sort that cuts a list of \( n \) items in two halves by a walk to its middle, sorts the two recursively and merges them by takeFirst() is stable and takes \( O( n \log n ) \) time and \( O( \log n ) \) space.
Indeed, the walk and the merge of a list of \( n \) items take \( O( n ) \), so that \( T( n ) = 2 T( n / 2 ) + O( n ) \), and the merge takes the item of the first half among equal ones, which keeps their order; the recursion is \( \lceil \log_2 n \rceil \) deep. List::mergeSort() runs it on the chain of the cells of the list, the halves cut by nil links and no list made, so that it relinks the cells of a pooled list as well; listSort() [see ListSort.h] is the bottom up natural merge sort, with \( n - 1 \) comparisons on a sorted list.
The SEList of Morin keeps its items in a doubly linked list of blocks, each a circular deque of at most \( b + 1 \) items, the blocks between the first and the last holding at least \( b - 1 \) items each; hence \( n \) items take \( n / ( b - 1 ) + 2 \) blocks at most, of exactly \( b + 1 \) places each for any \( b \), i.e., \( n + O( b + n / b ) \) places and \( O( n / b ) \) pointers, and the block of the rank \( i \) is reached from the nearer end through \( O( 1 + \min\{ i , n - i \} / b ) \) blocks.
Lemma 12 (spreading and gathering, section 3.3.5 of Morin). Starting from the empty list, \( m \) insertions and removals take \( O( b m ) \) time in their calls of spread() and gather().
Indeed, let a middle block be tight when it holds \( b - 1 \) or \( b + 1 \) items, and let \( \Phi \) be \( b \) times the number of tight blocks. An insertion or a removal that does not spread nor gather changes the size of one block by one and moves one item between neighbors, so that it makes at most one block tight, and raises \( \Phi \) by \( b \) at most; a spread is called on \( b \) blocks of \( b + 1 \) items and leaves \( b + 1 \) blocks of \( b \) items, and a gather on \( b \) blocks of \( b - 1 \) items (the first of \( b - 2 \)) and leaves \( b - 1 \) blocks, all of \( b \) items but the last, of \( b - 1 \), so that each lowers \( \Phi \) by \( b ( b - 2 ) \ge b^2 / 3 \) at least (\( b \ge 3 \)) and pays its \( O( b^2 ) \).
Unlike Morin's, the first and the last block of SEList hold from 1 to \( b + 1 \) items: an operation at an end adds a block when its block is full and drops it when it is empty, and never spreads nor gathers, so that the operations of a deque take \( O( 1 ) \) time independent of \( b \) (exercise 3.18), and those of a stack (exercise 3.17) a fortiori. With Morin's invariant, where only the last block is free, the stack takes \( O( 1 ) \) amortized time as well: a push on a full last block walks one block to the dummy and adds a block, and a pop that leaves the last block with fewer than \( b - 1 \) items borrows nothing, so that a sequence of pushes and pops never spreads nor gathers; the deque needs the relaxation at the front too, since a removal at the front of Morin's list shifts one item out of each of the blocks that follow, up to \( b \) of them.
The discussion of chapter 3 of Morin mentions the XOR list, whose cell keeps \( \mathit{prev} \oplus \mathit{next} \), the exclusive or of the addresses of its neighbors: a walk that knows where it comes from finds where it goes by one exclusive or, both ways, since \( ( \mathit{prev} \oplus \mathit{next} ) \oplus \mathit{prev} = \mathit{next} \), and the list reversed is the same list read from its other end, which XorList::reverse() does in \( O( 1 ) \). The same identity, \( x \oplus x = 0 \) with \( \oplus \) associative and commutative, swaps two integers with no third (exercise 3.19, xorSwap()), except when both are the same variable, which the three exclusive ors set to 0.
Exercise 1.6 asks for reference realizations of LIST, USET and SSET on an array, the oracles of the tests: ArraySequence for the first and the ArrayUSet and ArraySSet of SetInterfaces.h for the others (see Theory of sets). Exercise 1.7 asks how to make them faster: the shifts of a list by block moves and on the shorter side (RingDeque), the find() of an SSET by binary search on the sorted array, and its insertions by one memmove(), as ArraySSet does; the other realizations of the table above are the answers of chapters 2 and 3.
rotateArray() (exercise 2.4) rotates an array by three reversals: with \( a = X Y \), \( |Y| = r \), the reversal of the whole gives \( Y^R X^R \), and reversing each part gives \( Y X \), i.e., each item \( r \) places on, with \( n \) swaps at most. rotate() on an IndexedList with no rotate() of its own follows instead the \( \gcd( n , r ) \) cycles of the permutation \( i \mapsto ( i + r ) \bmod n \), each item moved once, plus one move per cycle.
Three sequences of Morin, Open Data Structures, reach an item by its rank in \( O( \log n ) \) expected time: SkipListSequence, the SkiplistList of section 4.3, whose links carry their widths, the number of items they jump over; TreapList, the list on a treap of exercise 7.11, whose nodes carry the sizes of their subtrees; and, for the order between two items rather than the access by rank, OrderMaintenanceList, the Sequence of exercise 8.11; the shuffle of exercise 7.4 closes the section.
Lemma 13 (the widths). In SkipListSequence, if the link of each node \( x \) on the level \( l \) has the width \( \mathrm{index}( x.\mathit{next}[ l ] ) - \mathrm{index}( x ) \), the head having the index \( -1 \) and nil the index \( n \), then the search of the index \( i \) that sums the widths and goes right while the sum stays at most \( i \) ends at the item of index \( i \), in \( O( \log n ) \) expected time, and an insertion, a removal, a truncation and an absorption keep the widths in \( O( \log n ) \) expected time.
Indeed, the sum of the widths along the search is the index of the node reached, so the search is that of a skip list whose keys are the indices, and Lemma 7 of Ordered dictionaries and tries bounds it. An insertion at \( i \) shifts by one the indices from \( i \) on: a link that passes over the new node grows by 1, and a link that the new node splits, from \( x \) of index \( j \), becomes two of widths \( i - j \) and the rest; the removal is the reverse. A truncation at \( i \) cuts on each level the link that crosses the index \( i \) and gives its end to the head of the new list, with the width reduced by \( i \); an absorption walks to the last node of each level, \( O( \log n ) \) steps in expectation since the walk is the search of the index \( n - 1 \), and links it to the first node of that level of the other list. The links to nil keep their widths, to the index \( n \), so that no level needs a special case.
TreapList reads the rank of a node as the size of the left subtrees passed on the right along its path; its shape is that of a treap on the indices, a random binary search tree of expected depth \( O( \log n ) \) whatever the order of the operations (Lemma 7.1 of Morin), and its split and join at an index are those of a treap on the keys.
The solution that exercise 8.11 has in mind labels each node of a scapegoat tree by its path, so that the order is a comparison of two words: the root has the label \( 2^{63} \) and the children of a node of label \( \ell \), whose lowest bit set is \( 2^j \), the labels \( \ell \pm 2^{j-1} \), which keeps the labels in symmetric order for a tree of height up to 63; a rebuild relabels the subtree it rebuilds inside its own \( O( s ) \), while a rotation would change the labels of a whole subtree, which is why the exercise sits in the chapter of the partial rebuilding, and an insertion costs \( O( \log n ) \) amortized (Lemma 10 of The trees of Open Data Structures). OrderMaintenanceList does better, \( O( 1 ) \) amortized, by the list labeling of Bender, Cole, Demaine, Farach-Colton and Zito on two levels: buckets of at most \( B = 64 \) consecutive elements with local labels, and labels of the buckets in \( [ 0 , 2^{63} ) \), kept by the rule of the densities. A new bucket takes the middle of the gap after its predecessor \( b \) if the gap is not empty; otherwise, for \( i = 1 , 2 , \ldots \), the range \( R_i \) of the \( 2^i \) labels aligned on \( 2^i \) that holds the label of \( b \) is overflowing if its buckets, the new one included, are more than \( ( 2 / T )^i \), i.e., if its density exceeds \( T^{-i} \), with \( T = 1.4 \); the first range that does not overflow is labeled again with equal gaps, of at least \( 2^i / ( 2 / T )^i = T^i \ge 1 \).
Lemma 14 (the densities). The insertion of a bucket writes at most \( 1 + 63 \cdot 2 / ( T - 1 ) + 1 = 317 \) labels of buckets amortized, with \( T = 1.4 \), whatever the removals among the insertions.
Indeed, a relabeling of \( R_i \) writes \( m \le ( 2 / T )^i \) labels, and it happens because \( R_{i-1} \) overflows, with more than \( ( 2 / T )^{i-1} \) buckets. The last time that a range containing \( R_{i-1} \) was labeled again, the gaps were equal, and the half \( R_{i-1} \) of a range of level at least \( i \) received at most half of its buckets plus one, at most \( ( 2 / T )^{i-1} / T + 1 \); hence at least \( ( 2 / T )^{i-1} ( 1 - 1 / T ) - 1 \) insertions have gone into \( R_{i-1} \) since then (a removal only lowers its count), and each of them pays \( ( 2 / T ) / ( 1 - 1 / T ) = 2 / ( T - 1 ) = 5 \) labels to the level \( i \), the extra one being covered by the 1 of the bound. An insertion lies in one range of each of the 63 levels, and pays once per level. The universe of \( 2^{63} \) labels holds \( ( 2 / T )^{63} \approx 5.8 \cdot 10^9 \) buckets, the most for which \( R_{63} \) does not overflow.
A bucket is labeled again with equal gaps of more than \( 2^{56} \) when the gap of a new element is empty, which needs 56 halvings of one gap, i.e., 56 insertions into the bucket since its last relabeling (the removals only widen the gaps); it splits into halves of 32 and 33 elements when it reaches \( B + 1 = 65 \), which needs 32 insertions into it since it was made, and writes 65 local labels and the labels of Lemma 14 for the new bucket. Hence an insertion writes, amortized, its own label, at most \( 64 / 56 \) for the relabelings of its bucket and \( ( 65 + 317 ) / 32 \) for the splits, fewer than 15 labels, a constant that the bound \( \log_2 m < 63 < B \) makes independent of \( n \); relabelWork() counts them, and the test of the exercise checks that their mean stays below 8 from \( 2^{12} \) to \( 2^{17} \) insertions in the worst patterns. A removal unlinks its element, and its bucket if it empties, in \( O( 1 ) \) in the worst case, and testBefore() compares the labels of the two buckets, or the local labels within one bucket.
Lemma 15 (the shuffle, exercise 7.4 of Morin). The shuffle of Fisher and Yates in the form of Durstenfeld, shuffleFast() [see RandomGenerators.h], gives each of the \( n! \) orders with probability \( 1 / n! \), in \( n - 1 \) swaps.
Indeed, by induction on the places from the last: the item put in the place \( i \) is drawn uniformly among the \( i + 1 \) items of \( A[ 0 .. i ] \), independently of the draws for the places above \( i \), and each order is the outcome of exactly one sequence of draws, of probability \( \prod_{i=1}^{n-1} \frac{1}{i + 1} = \frac{1}{n!} \). The draw below \( m \) multiplies a word of 64 bits by \( m \) and takes the high word, rejecting the \( 2^{64} \bmod m \) values of the low word that would bias it (Lemire), which needs a division only when the low word is below \( m \), with probability \( m / 2^{64} \), and shuffleFast() draws several indices from one word when their product fits; the shuffle() of RandomNumbers.h, Algorithm 3.4.2P of Knuth, draws by the same method on a generator of 64 bits and by rejection on a narrower one, never by \( g() \bmod j \), which carries the bias of the remainder.
ObservableArray< T , Policy > is a vector whose writes go through a subject policy of Modification.h (see Typed modifications): the handle of a value is its index, which is also its key, set() and add() send \( \mathrm{Assigned}( i , u , v ) \), push_back() sends \( \mathrm{Inserted}( n , n , v ) \) and pop_back() \( \mathrm{Erased}( n - 1 , n - 1 , v ) \), clear() and assign() send \( \mathrm{Cleared} \) and \( \mathrm{Rebuilt} \). Since the indices that it emits are those of the end only, an index never changes meaning between two events of a batch, and the coalescing of Lemma 1 of Typed modifications applies as it does to a structure with stable handles (an erasure and an insertion at the same index become one \( \mathrm{Assigned} \), whose events the array emits). With NoObservers every write is that of the vector, which the check of zero cost confirms by the instructions and by the code.
Fenwick< G > keeps the values \( a_0 , \ldots , a_{n-1} \) of a monoid \( ( G , \oplus , e ) \) (see The algebra of the aggregates) and the nodes
\[ t_j = a_{j - \lambda( j )} \oplus \cdots \oplus a_{j - 1} , \qquad j = 1 , \ldots , n , \tag{8} \]
with \( \lambda( j ) \) the lowest bit of \( j \), i.e., the largest power of 2 that divides it (Fenwick).
Lemma 16 (the nodes of Fenwick). (i) For \( 0 \le r \le n \), the sequence \( j_1 = r \), \( j_{k+1} = j_k - \lambda( j_k ) \), ends at 0 after at most \( \lfloor \log_2 r \rfloor + 1 \) steps, and \( a_0 \oplus \cdots \oplus a_{r-1} = t_{j_m} \oplus \cdots \oplus t_{j_1} \). (ii) For \( j \ge 1 \), \( t_j = t_{j - \lambda( j ) / 2} \oplus \cdots \oplus t_{j - 2} \oplus t_{j - 1} \oplus a_{j - 1} \), the nodes \( t_{j - 2^k} \), \( 2^k < \lambda( j ) \), taken by decreasing \( k \). (iii) The nodes that contain \( a_i \) are those of the sequence \( j_1 = i + 1 \), \( j_{k+1} = j_k + \lambda( j_k ) \), while \( j_k \le n \), at most \( \lfloor \log_2 n \rfloor + 1 \) of them.
Indeed, (i): each step clears the lowest bit set of \( j \), so that the steps are at most the bits set in \( r \), and the node \( t_{j_k} \) covers the indices \( [ j_{k+1} , j_k ) \) by (8); these intervals are consecutive and, from \( k = m \) down to 1, go from 0 to \( r \), so that their combination in this order is the prefix, by associativity alone. (ii): the indices \( [ j - \lambda( j ) , j - 1 ) \) split into the intervals \( [ j - 2^{k+1} , j - 2^k ) \) for \( 2^k < \lambda( j ) \), the bits below the lowest of \( j \) being zero, and \( \lambda( j - 2^k ) = 2^k \), so that the interval of \( 2^k \) is that of \( t_{j - 2^k} \); by decreasing \( k \) they go from left to right, and \( a_{j - 1} \) is last. (iii): \( a_i \) is in \( t_j \) iff \( j - \lambda( j ) \le i < j \), so that the least such \( j \) is \( i + 1 \). Let \( t_j \) contain \( a_i \). For \( j' = j + m \), \( 0 < m < \lambda( j ) \), the lowest bit of \( j' \) is that of \( m \), and \( j' - \lambda( j' ) \ge j' - m = j > i \), so that \( t_{j'} \) does not contain \( a_i \); for \( j' = j + \lambda( j ) \) the addition carries, \( \lambda( j' ) \ge 2 \lambda( j ) \), and \( j' - \lambda( j' ) \le j - \lambda( j ) \le i \), so that \( t_{j'} \) contains it. Thus \( \lambda \) at least doubles at each step. Hence prefix( r ) costs \( O( \log n ) \) combinations, the nodes are built in increasing \( j \) in \( \sum_{j \le n} \log_2 \lambda( j ) = O( n ) \), and a new value \( a_n \) gets its node \( t_{n+1} \) by (ii) in \( O( \log n ) \), with no other node changed; the removal of \( a_{n-1} \) drops \( t_n \) only.
Lemma 17 (the updates of Fenwick). Let \( a_i \) become \( v \). (i) If \( G \) is an abelian group, replacing each node \( t_j \) of Lemma 16 (iii) by \( t_j \oplus \delta \), \( \delta = a_i^{-1} \oplus v \), gives the nodes of the new values, in \( O( \log n ) \) combinations. (ii) If \( G \) is a commutative monoid and \( v = a_i \oplus d \), the same with \( \delta = d \). (iii) For any monoid, recomputing those nodes by Lemma 16 (ii) in increasing \( j \) gives the new nodes, in \( O( \log^2 n ) \) combinations.
Indeed, a node that does not contain \( a_i \) does not change, and one that does is \( x \oplus a_i \oplus y \), which (i) and (ii) update by Lemma 3 (i) and (ii) of The algebra of the aggregates. For (iii), the nodes of Lemma 16 (ii) that \( t_j \) combines have indices less than \( j \), so that those that contain \( a_i \) have been recomputed before \( t_j \) when the nodes are taken in increasing order, and the others are unchanged; each recomputation takes \( O( \log n ) \) combinations, for at most \( \lfloor \log_2 n \rfloor + 1 \) nodes.
For a group, the range \( a_l \oplus \cdots \oplus a_{r-1} \) is \( \pi_l^{-1} \oplus \pi_r \), \( \pi_r \) the prefix of length \( r \), since \( \pi_r = \pi_l \oplus ( a_l \oplus \cdots \oplus a_{r-1} ) \), which needs no commutativity. When the values are floating point, the differences of (i) accumulate the rounding of every update, and the tree is rebuilt from its values every period() such updates, at \( O( n ) \) per rebuild, i.e., \( O( 1 ) \) amortized when the period is at least \( n \).
FenwickObserver< G > is an observer of an array of values of \( G \) that applies \( \mathrm{Assigned}( i , u , v ) \) by the update of Lemma 17, \( \mathrm{Inserted} \) and \( \mathrm{Erased} \) at the end by Lemma 16, and \( \mathrm{Cleared} \) by emptying the tree, and on \( \mathrm{Rebuilt} \) marks its tree stale: it ignores the events until its next query, at which it builds the tree again from the vector of the array, in \( O( n ) \).
Lemma 18 (the observer of the prefixes). After each event sent outside a batch and after each batch, the tree of FenwickObserver, at its next query, is the tree of the values of the array.
Indeed, by induction on the events received. Outside a batch each event starts from the state of the array that the observer knows, and Lemmas 16 and 17 keep the tree equal to that of the array; a batch delivers its net effect, which is a history from the state before the batch to the state after it by Lemma 1 of Typed modifications, with \( \mathrm{Cleared} \) or \( \mathrm{Rebuilt} \) first if there was one. After \( \mathrm{Rebuilt} \) the events are ignored and the tree is built at the next query from the array as it is then, i.e., after every event delivered so far, which is the state that a history that went on from there would reach.
The test fenwick-observer checks Lemma 18 by Shadow of Modification.h, which sends every event to the observer and to one that recomputes each prefix by a scan of its own copy of the values, and compares their answers at each query, on random writes, appends, removals, batches, clearings and rebuildings.