|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/queue realize the QUEUE of section 4.3.1 of the book, with a circular vector (section 4.3.3) and with a singly linked list (exercise 4.10), the DEQUEUE of exercise 4.9, a double ended queue on a circular vector that doubles, a queue with no duplicates, and two algorithms that use a queue through its operations alone. 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 arithmetic of the circular vectors (see Circular vectors), the queues with no duplicates and the algorithms on a queue (see Queues with no duplicates and algorithms on a queue), and the aggregate of a sliding window over a monoid (see The aggregate of a sliding window). The pseudocode of each operation is on the page of its header, in the comment of its function, together with the section of the book that it follows.
A queue is a sequence of items to which items are added at one end, the back, and from which they are removed at the other, the front: the first item added is the first removed (FIFO, first in first out). The QUEUE of the book has enqueue(), which adds an item at the back, dequeue(), which removes the item at the front and returns it, top(), which reads it, and empty(); its axioms are \( \mathrm{top}( \mathrm{enqueue}( Q , v ) ) = \mathrm{top}( Q ) \) and \( \mathrm{dequeue}( \mathrm{enqueue}( Q , v ) ) = \mathrm{enqueue}( \mathrm{dequeue}( Q ) , v ) \) for \( Q \) not empty (see Abstract data types and their axioms, and the concept Queue of ADT.h). A queue is what a computation needs when it serves its requests in the order of their arrival, e.g., the visit in breadth of a graph, which examines the nodes by increasing distance from the root because they leave the queue in the order in which they were reached. A double ended queue, or deque, is changed at both ends, and is a stack when used at one end only and a queue when items enter at one end and leave at the other.
| Symbol | Meaning |
|---|---|
| \( n \) | the number of items of a queue |
| \( m \) | the number of places of a circular vector, its capacity |
| \( h \) | the place of the front in a circular vector |
| \( A[ 0 .. m - 1 ] \) | a circular vector, the place 0 following the place \( m - 1 \) |
| Realization | Representation | Space | Operations at the ends | Capacity |
|---|---|---|---|---|
| ArrayQueue | a circular vector | \( \Theta( m ) \) | \( O( 1 ) \) | \( m \), fixed |
| LinkedQueue | a singly linked list with pointers to its first and last cells | \( \Theta( n ) \) | \( O( 1 ) \) | none |
| Dequeue | a bidirectional list with a sentinel | \( \Theta( n ) \) | \( O( 1 ) \) at both ends | none |
| RingDeque | a circular vector of \( 2^j \) places that doubles | fewer than \( 2 N + 8 \) places, \( N \) the most items held | \( O( 1 ) \) amortized at both ends, \( O( 1 ) \) by rank | none |
| UniqueQueue | a bidirectional list, with no duplicates | \( \Theta( n ) \) | \( O( n ) \) to enqueue, \( O( 1 ) \) to dequeue | none |
| RandomQueue | a vector, the item out drawn uniformly | \( \Theta( n ) \) | \( O( 1 ) \) amortized | none |
| MinQueue | two stacks with the minimum | \( \Theta( n ) \) | \( O( 1 ) \) amortized, min() in \( O( 1 ) \) | none |
| MinDeque | two stacks with the minimum, back to back | \( \Theta( n ) \) | \( O( 1 ) \) amortized at both ends, min() in \( O( 1 ) \) | none |
| RealTimeMinQueue | two arrays with the minimum, the back moved to the front by the rotation of Hood and Melville | \( \Theta( n ) \) | \( O( 1 ) \) in the worst case, min() in \( O( 1 ) \) | none |
| RealTimeMinDeque | two arrays with the minimum, back to back, rebuilt globally | \( \Theta( n ) \) | \( O( 1 ) \) in the worst case at both ends, min() in \( O( 1 ) \) | none |
A singly linked list is a queue when the items enter after its last cell and leave from its first one, since the removal of the first cell and the insertion after the last one need no predecessor (see Lemma 1 of Theory of sequences and lists); the list keeps a pointer to each of the two cells, and an empty list has both nil. The deque needs instead the removal of the last cell too, i.e., its predecessor, which a bidirectional list has at hand. Among the vectors, a queue whose items stayed in the places from 0 on would move all of them at each dequeue(), i.e., \( \Theta( n ) \); a circular vector lets the front move instead, as follows.
In a circular vector \( A[ 0 .. m - 1 ] \) the place 0 follows the place \( m - 1 \), and a queue of \( n \le m \) items with its front at the place \( h \) holds the item of rank \( i \) from the front, for \( 0 \le i < n \), at the place
\[ ( h + i ) \bmod m , \tag{1} \]
so that its back is at \( ( h + n - 1 ) \bmod m \) and the next item enters at \( ( h + n ) \bmod m \). A dequeue() advances \( h \) by one place and an enqueue() writes after the back, each in \( O( 1 ) \); the items run through the vector as a band that wraps around its end, and the vector is full when \( n = m \), which a vector with the two indices of the front and of the back alone could not tell from the empty one (both have the indices equal), whence the count \( n \) kept beside \( h \). Since \( h < m \) and \( n \le m \), the sum \( h + n \) is below \( 2 m \), and the modulo of (1) is a comparison and a subtraction rather than a division. A copy of ArrayQueue reads the items by (1) and writes them from the place 0 of its vector, \( h = 0 \), while a move takes the vector and leaves \( n = m = 0 \) behind, a queue that is empty and full at once, so that its contracts refuse both dequeue() and enqueue().
RingDeque takes \( m = 2^j \), so that the modulo is the mask \( m - 1 \), and keeps the front and the back as counters modulo \( 2^{64} \) whose difference is \( n \): an insertion at the back and a removal from the front change one counter each, and the place of a counter \( c \) is \( c \mathbin{\&} ( m - 1 ) \). When the vector is full it doubles, and its items are moved in order to the front of the new vector, in at most two contiguous pieces, \( A[ h .. m ) \) and the part that wrapped around; by the argument of the vectors that double (see Vectors that change their size), \( n \) insertions move fewer than \( 2 n \) items. An insertion at the front of a full deque puts the new item at the last place of the new vector, and the front there, which (1) makes the place before the place 0. Unlike a deque that only grows at its back, the places freed at one end serve the insertions at the other, so that a deque used as a queue in a steady state never moves its items.
UniqueQueue refuses the duplicates by one of two policies: IGNORE_NEW does not enqueue an item already in the queue, so that each item keeps the place of its first arrival, as the visits of a graph want it, and FORGET_OLD removes the old copy and enqueues the item at the back, so that it keeps the place of its last arrival, as a cache of the least recently used items wants it. Either way enqueue() must find the copy, which on a list costs \( O( n ) \) comparisons; the invariant is that no item occurs twice, which requires an equality that is an equivalence (an item unequal to itself, e.g., a NaN, would be enqueued again and again).
The functions of QueueAlgorithms.h act on a queue through its operations alone. Moving the positive items of a queue \( q \) to another one in their order dequeues each item of \( q \) once, \( O( n ) \); copying them instead, with \( q \) left as it was, enqueues each item in an auxiliary queue as it is dequeued and moves the auxiliary queue back, which, by the order FIFO of both, restores the order of \( q \), i.e., \( O( n ) \) time and space. A queue cannot be restored by rotating it alone, i.e., by enqueueing each item again in \( q \) as it is dequeued, without knowing how many items it holds, which the QUEUE of the book does not say.
RingDeque is also the ArrayDeque of section 2.4 of Morin's Open Data Structures, a LIST by rank whose insert( i , v ) and erase( i ) move the \( \min\{ i , n - i \} \) items of the shorter side (see Lists by rank (Morin's book) for the other deques of chapter 2 of Morin and the costs of their operations by rank).
The RandomQueue of exercise 2.2 keeps its items in a vector in no order: push() appends, pop() draws a place \( j \) uniformly, exchanges it with the last place and removes the last one, in \( O( 1 ) \). Each item inside is equally likely to come out, whatever the history, since the draw does not depend on the order of the vector. The place is drawn by the multiplication of Lemire: with \( w \) a word of 64 bits uniform and \( w \cdot n = 2^{64} h + l \), the high half \( h \) is uniform in \( [ 0 , n ) \) once the words with \( l < ( 2^{64} - n ) \bmod n \) are rejected, since each value of \( h \) is then the image of exactly \( \lfloor 2^{64} / n \rfloor \) words; the rejection happens with probability below \( n / 2^{64} \), and the division that computes the threshold only when \( l < n \), i.e., almost never.
Lemma 1 (two stacks make a queue, exercise 3.15). Let MinQueue enqueue on a stack \( I \) and dequeue from a stack \( O \), moving all the items of \( I \) to \( O \) when \( O \) is empty. Then the items leave in the order in which they entered, \( m \) operations take \( O( m ) \) time, and the least item is the lesser of the minima of the two stacks, each kept by a MinStack (see The stacks of Morin's book).
Indeed, the move reverses \( I \), so that the oldest item is on top of \( O \), and the items of \( O \) are all older than those of \( I \); each item is pushed and popped twice at most, once on each stack, which bounds the total work by \( 4 m \) operations of the stacks. The worst case of one operation is \( \Theta( n ) \), which the real-time queue of Hood and Melville removes by spreading the reversal over the operations (see The minimum in constant worst-case time).
Lemma 2 (two stacks make a deque, exercise 3.16). Let MinDeque keep a stack \( F \) with the front on top and a stack \( B \) with the back on top, and let a removal from an empty side deal the \( k \) items of the other side again, the \( \lceil k / 2 \rceil \) nearer to the end of the empty side to it. Then \( m \) operations take \( O( m ) \) time.
Indeed, let \( \Phi = 2 \, | |F| - |B| | \). An operation that does not deal costs 1 and changes \( \Phi \) by 2 at most; a deal of \( k \) items costs \( O( k ) \) and is called when one side is empty, i.e., \( \Phi = 2 k \), after which \( \Phi \le 2 \) (the removal that follows it changes it by 2 more at most), so that the drop of \( \Phi \) pays for it. As for the queue, the least item is the lesser of the minima of the two stacks.
Lemmas 1 and 2 bound sequences, not operations: one dequeue() of MinQueue may move the whole back, one removal of MinDeque deal a whole side. RealTimeMinQueue and RealTimeMinDeque spread that work over the operations that precede the moment it is needed, on arrays that hold in each cell the place of the least item at or below it, allocated with their final size when the work starts and emptied one cell at a time, so that no operation copies, moves or destroys more than a constant number of items (an allocation counted as \( O( 1 ) \)).
Lemma 3 (the rotation of Hood and Melville). Let RealTimeMinQueue keep the front \( F \) and the back \( R \), and start a rotation when \( |R| = |F| + 1 \): \( R \) is frozen, a new back takes the insertions, and a new front \( N \) is built from the bottom, by three moves per operation, first the frozen back from its top and then \( F \) from its bottom, while the removals take the top of \( F \); when the moves of \( F \) meet its top, \( N \) is the front. Then the front never empties during a rotation, every operation costs \( O( 1 ) \) in the worst case, and the back has at most \( |F| + 1 \) items when the next rotation starts.
Indeed, with \( f = |F| \) at the start, the operation that starts the rotation and the \( k \) after it make \( 3 ( k + 1 ) \) moves and at most \( k \) removals, and the \( f + 1 \) moves of the back are done for \( k \ge ( f + 1 ) / 3 - 1 \), when \( F \) still has \( f - k > 0 \) items; the moves of \( F \) go up from its bottom and the removals down from its top, so that they meet, after at most \( \lceil ( 2 f + 1 ) / 3 \rceil \) operations in all. \( N \) holds then the remaining items of \( F \) above those of the frozen back, in the order of the queue, \( 2 f + 1 - d \) of them after \( d \) removals, while the new back holds at most the \( \lceil ( 2 f + 1 ) / 3 \rceil - d \) insertions, fewer; hence the next rotation starts again with \( |R| = |F| + 1 \), and the arrays allocated at the start, of \( f + |R| \) and \( f + |R| + 2 \) cells, are large enough. The least item is the least of the minima of the parts: \( F \) (whose least place, if it has moved, is found in \( N \) at the same offset after the frozen back), the frozen back, \( N \) and the new back, each in \( O( 1 ) \) by the place of its top cell.
Lemma 4 (the global rebuilding of a deque). Let RealTimeMinDeque keep the stacks \( F \) and \( B \) as MinDeque does, and start a rebuild when one side \( G \) has \( 3 m + 2 \) items, \( m \) those of the other side \( S \), or a side fills half its array: two arrays of \( 2 n_0 + 16 \) cells take copies, twelve per operation, of the \( t = |G| - \lceil n_0 / 2 \rceil \) bottom items of \( G \) and of \( S \) for the new \( S \), and of the rest of \( G \) for the new \( G \), as prefixes that a removal shortens by one when it goes below their end. Then, for \( n_0 \ge 32 \), the rebuild ends within \( n_0 / 11 + 2 \) operations, during which no side empties and \( G \) keeps its \( t \) bottom items, every operation costs \( O( 1 ) \) in the worst case, and the next rebuild comes \( \Omega( n_0 ) \) operations later.
Indeed, the copies are at most \( n_0 \) plus one per insertion during the rebuild, so that \( k \) operations finish them once \( 12 k \ge n_0 + k \), i.e., \( k \le n_0 / 11 + 1 \) after the operation that starts it. At the start of a rebuild by the sizes, \( m \ge ( n_0 - 4 ) / 4 \ge 7 \), more than the removals from \( S \), and \( G \) keeps \( \lceil n_0 / 2 \rceil \) items above its bottom \( t \), more than the removals from it; a rebuild by the room starts with sides that differ by a factor 3 at most, and the half of the arrays that is free holds the insertions. Since the old stacks keep all their cells below the tops, their minima stay right, and the operations act on them as on MinDeque with no deal. When the prefixes reach the tops the new arrays replace the old ones, each side with about \( n_0 / 2 \) items, within \( n_0 / 11 + 2 \) of it, and with room for \( n_0 + 8 \) before half; a new rebuild needs \( |G| - 3 |S| \) to grow from about \( - n_0 \) to 2, by 3 at most per operation, or a side to grow by about \( n_0 / 2 \), i.e., \( \Omega( n_0 ) \) operations, more than the \( ( 2 n_0 + n_0 / 11 + 2 ) / 12 \) that destroy the old arrays, twelve cells per operation. A deque of fewer than 32 items is rebuilt at once, in \( O( 1 ) \). The items are copied, since the old stacks stay in use during the rebuild, while the queue moves them.
SlidingAggregate< G , Policy > is a queue of values \( x_1 , \ldots , x_n \) of a monoid \( ( G , \oplus , e ) \), from the front to the back, with aggregate(), the combination \( \alpha = x_1 \oplus \cdots \oplus x_n \) in this order (\( e \) if \( n = 0 \)), which the queues with the minimum above compute for \( \oplus = \min \). The algebra and the policy choose one of four algorithms (see The algebra of the aggregates), whose correctness follows.
Lemma 5 (subtract-on-evict). In a group, the aggregate kept as \( s \gets s \oplus x \) at each insertion of \( x \) at the back and \( s \gets x_1^{-1} \oplus s \) at each removal of \( x_1 \) from the front equals \( \alpha \), each operation in \( O( 1 ) \) combinations.
Indeed, by induction on the operations, from \( s = e \): an insertion makes \( s = x_1 \oplus \cdots \oplus x_n \oplus x \), and a removal makes \( x_1^{-1} \oplus x_1 \oplus ( x_2 \oplus \cdots \oplus x_n ) \), i.e., Lemma 3 (iii) of The algebra of the aggregates; no commutativity is used, and with floating point values the aggregate is recomputed from the items every period() removals, at \( O( 1 ) \) amortized cost when the period is at least \( n \).
Lemma 6 (the monotone deque). In a selective monoid, let the deque \( C \) of the candidates be updated at each insertion of \( x \) by removing from its back each \( c \) with \( c \oplus x = x \) and then appending \( x \), and at each removal of \( x_1 \) by removing its front if it is \( x_1 \) (as an item, by its number). Then, for every \( l \), the combination of the candidates of numbers at least \( l \), in their order, is \( x_l \oplus \cdots \oplus x_n \), and the front of \( C \) is \( \alpha \); each operation costs \( O( 1 ) \) amortized.
Indeed, by induction on the operations. Let \( \Gamma_l \) be the combination of the candidates of numbers at least \( l \). At an insertion of \( x \), a removed candidate \( c \) is the last one, so that \( \Gamma_l = \Gamma' \oplus c \) with \( \Gamma' \) the candidates before it, and \( x_l \oplus \cdots \oplus x_n \oplus x = \Gamma' \oplus ( c \oplus x ) = \Gamma' \oplus x \); once no candidate is removed, appending \( x \) gives \( \Gamma_l \oplus x \), which is the new suffix. At a removal the suffixes from \( l \ge 2 \) are those of before, and the candidate of number 1, if there is one, goes. Two consecutive candidates \( c , c' \) became consecutive when \( c' \) was appended with \( c \) last, and then \( c \oplus c' \ne c' \), i.e., \( c \oplus c' = c \) by selectivity; hence, combining from the back, \( \Gamma_1 \) is the front of \( C \). Each item enters and leaves \( C \) once.
Lemma 7 (Two-Stacks Lite). In any monoid, let the items be in one deque whose first \( m \) items carry the aggregates \( S_k = x_k \oplus \cdots \oplus x_m \), \( k \le m \), and let \( b \) be the aggregate of the others; an insertion combines its item into \( b \), and a removal with \( m = 0 \) first makes all the items the first part, computing \( S_n , S_{n-1} , \ldots , S_1 \) from the back and setting \( b = e \). Then \( \alpha = S_1 \oplus b \), and each operation costs \( O( 1 ) \) amortized (Tangwongsan, Hirzel and Schneider).
Indeed, \( S_1 \) covers the items of the first part and \( b \) those after it, in the order of the queue; a removal drops \( x_1 \) and \( S_1 \), and the next \( S_2 \) is still the aggregate of the first part, while an insertion extends \( b \) on the right. Each item enters the first part once, at the cost of one combination, which the potential \( n - m \) pays.
Lemma 8 (the real-time window). Let the queue be kept as RealTimeMinQueue keeps it (Lemma 3), each cell of a front (\( F \), \( N \)) holding the aggregate of its item and of the cells below it with the item first, \( x \oplus \sigma \), and each cell of a back (\( R \), the frozen \( R' \)) the aggregate with the item last, \( \sigma \oplus x \). Then, with \( \hat P \) the aggregate in the top cell of the part \( P \) and \( \hat N_k \) that of the cell \( k - 1 \) of \( N \), \( k = \min( r_0 , |N| ) \),
\[ \alpha = \hat F \oplus \hat R' \oplus \hat N_k \oplus \hat R , \]
the parts that are empty left out, and every operation costs \( O( 1 ) \) in the worst case.
Indeed, the cost is that of Lemma 3, plus one combination per move. The top cell of \( F \) holds the aggregate of the cells from 0 to its top, in the order of the queue, including the bottom cells already moved into \( N \), whose items are still in the queue right after those of the cells that remain (the aggregate was computed when the cells were pushed, and the moves do not change it), and excluding the items removed from the top. The top of \( R' \) covers the items of the frozen back that are not yet moved, which precede in the queue those moved; the first \( k \) cells of \( N \) hold these, the last item of the back at the bottom, so that the aggregate of the cell \( k - 1 \), the item first, combines them in the order of the queue; the cells of \( N \) above \( r_0 \) hold items of \( F \) already counted in \( \hat F \). The new back follows. When the rotation ends \( N \) is the front, its top cell covering all its items.
The minimum of RealTimeMinQueue is Lemma 8 for the selective monoid of the minima, where the parts may overlap since \( \min \) is idempotent, which is why it reads the least place of \( F \) in \( N \) instead. MinQueue and RealTimeMinQueue stay, since they also take an order that is an object and give the least item by reference, which a monoid whose combination returns a value cannot; the test sliding-minqueue checks that the windows of the minima agree with them.