This chapter describes a number of basic data structures used by the various algorithms and as building blocks within more complex data structures.

The list is represented by a vector $\next$, which identifies the next item in the list. So for example $\next[7] = 5$ as you would expect. Notice that $\next[2] = 0$ to indicate the end of the list. For the integers in $1\ldots 10$ that are not in the list, the value of $\next$ is $-1$. This enables a constant-time test to determine if a given value is in the list. A list like this could be used to represent a queue containing some of the vertices in a graph. The linked representation allows one to easily remove the first element or add a new element to the end.
Here is another example of an index-based data structure, that defines a collection of disjoint lists that partition the index set $1\ldots 12$ into the six subsets $\{[1, 6, 3], [4], [2, 7], [8], [11, 9], [5, 12, 10]\}$. This list is doubly-linked with the $\next$ and $\prev$ arrays defining the neighbors of each list item. The colors different highlight items in the same list.

Note that the $\next$ value for the last item on each list is 0 to mark the end of the list. However, the $\prev$ value of the first item on each list is not 0. Instead, it points to the last item in the list, enabling easy access to the last item from the first. This data structure is called a $\ListSet$; the provided operations on list set objects are described below.
All the algorithms and data structures described here have been implemented as Javascript modules. The example below illustrates the use of the index list and list set data structures plus another data structure for an undirected graph. Note that the code below is enclosed in a scrollable text area.
The function $\components$ takes two arguments, an undirected graph and a trace flag used to enable the production of a trace string (the code to generate the trace string has been omitted for clarity). It identifies the individual connected components of the graph and returns the number of components, a $\ListSet$ object that contains a list of the vertices in each component and the trace string.
The $\ListSet$ object $\comps$ is defined on the integers 1 to $n$, where $n$ is the number of vertices in the $\Graph$ object $g$. The outer loop scans the set of vertices looking for a vertex $s$ which is not in any component already identified, while the inner loop implements a breadth-first search over the component containing $s$, combining all of its vertices into a single list in $\comps$. The $\singleton()$ method of the $\ListSet$ object returns true if its argument is the only item in its list. The $\join()$ method combines two lists, where each list is identified by its first item. The $\enq()$ method of the $\List$ object adds an item to the end of the list and the $\deq()$ method removes the first item. The $\firstAt()$ and $\nextAt()$ methods of the $\Graph$ object are used to traverse an adjacency list for a specified vertex, while $\mate(u,e)$ returns the endpoint of edge $e$ that is not $u$.
There is a simple web application that allows you to examine the code for any of the provided modules and run the code in a browser.

When the app is first opened, the top text area is available as a scratch pad that you can use to enter and run programs. To run the $\components$ module first copy and paste the following text into the top window.
let g = new Graph();
g.fromString('{a[b d e] b[a c f] c[b d f] d[a c e] e[a d] f[b c] '
+ 'g[h] h[g i] i[h]}');
log(g);
let [count,comps] = components(g)
log(count + ' ' + comps);
The $\fromString$ method initializes the graph object $g$
from a string, which specifies the graph as a set of adjacency
lists.
So for example, the initial portion of the provided argument
($a[b\;d\;e]$), specifies edges connecting vertex $a$ to
vertices $b$, $d$ and $e$.
One can use the more concise form
g.fromString('{a[b d e] b[c f] c[d f] d[e] g[h] h[i]}');
in which each edge appears just once.
The log() method can be viewed as a shorthand for
console.log(). Its output appears in the bottom window.
If you click on the $\run$ button at right, the following text
will appear in the lower window.
{a[b d e] b[a c f] c[b d f] d[a c e] e[a d] f[b c] g[h] h[g i] i[h]}
2 {[a b c d e f][g h i]}
The first line shows the graph as a string.
The second shows the number of components and the vertices in each component.
If you replace the last three lines in the top window with
let [,,ts] = components(g,1) log(ts);and click on the $\run$ button agin, you will get
The provided trace output shows the vertex selected on each iteration of the inner loop, plus the contents of the queue and the non-singleton lists in $\comps$ at the end of the iteration.
The menus at the top right of the web app provide access to all the available code modules. The first two menus list the data structures and unit tests for each. The next two list the algorithms that use those data structures, along with their unit tests. When a unit test is displayed, you can run it using the $\run$ button. The last menu provides access to some common code modules. You can activate a menu by clicking on the button to its left, causing the selected item to be displayed. Selecting an item from a different menu activates that menu. Go back to the scratch pad by clicking on its button.
If you display the module testComponents and click on the run button, the program will run. By default, the only output is a brief informational message. The lines
let [k, ls, ts] = components(g, trace);
matches(k, 2, 'a1');
matches(ls, '{[a b c d e f] [g h i]}', 'a2');
run the $\components$ function and verify its output.
The $\matches$ function verifies that its first two
arguments are equal and prints an error message if they are not.
The error message includes string versions of the
first two arguments so that you can
see why the test failed.
The third argument is a tag that appears in the error message so
you can more easily identify which call to
$\matches$ triggered a given message.
A failed call to $\matches$ also triggers an exception
which terminates the test.
For example, if you change the 2 in the first call to $\matches$
to 3, you will get the message
Mismatch: a1 2 3
If you type “trace” into the textbox just above the run button and click it again, you will also see the trace string produced by the components module. This is an example of a general mechanism for supplying command-line arguments to unit tests that support them. Reviewing the code for the various code modules, will allow you to see exactly how they are implemented.
The web application, is available at
www.cse.wustl.edu/~jon.turner/grafalgo/jsThe provided code is also available as part of the Grafalgo library, which can be downloaded from
https://github.com/jonturner53/grafalgoThe library includes C++ implementations of most of the code described here, in addition to the Javascript version. The C++ version pre-dates the Javascript version. Do not expect them to fully consistent. There is also the beginnings of a Java version, which may (or may not) be completed at some point.
The $\List$ object can also be extended to associate a set of values with the list items. This enables the following method.
List Pair
The $\ListPair$ class defines two complementary lists over
the same index range. One is referred to as list 1,
the other as list 2. Initially, all items are in list 2.
List Set
The $\ListSet$ class implements a collection of disjoint
lists on a common index set $1\ldots n$.
Each list in the collection is identified by its first list item.
The primary methods are listed below.
Note that the usual per-method comments have been omitted above,
as they are somewhat repetitious in this context, and can distract
attention from the actual code. In general, the code modules that appear in
the remainder of the text are similarly abridged. One can always review
the complete code of any module using the web app.
Reversible Lists
The $\ReverseLists$ class is similar to $\ListSet$ in that it partitions the index range into a set of lists. The distinctive feature of the $\ReverseLists$ class is that its lists can be reversed in constant time. The new methods are listed below.
MergeSets
The $\MergeSets$ class defines a collection of disjoint sets
over the index set $1\ldots n$ and provides methods to efficiently identify
the subset containing a given item and to combine subsets.
Each subset is identified by one of its members.
The key methods are listed below.

The $\find$ method follows parent pointers up the tree to find the root and the $\merge$ operation combines two trees by directing the parent pointer of one of the two tree roots to the other, essentially making one tree a subtree of the other's root.
Two heuristics are used to make the data structure efficient. The merge-by-rank heuristic defines a property $\rank(i)$ for each item $i$ and uses it when combining trees to limit the depth of the trees. Initially, the $\rank$ values are 0 and when two trees are merged, the parent pointer of the tree root with the smaller rank is directed to the other root. If the two roots have equal ranks, the rank of the new root (chosen arbitrarily) is incremented. This procedure ensures that the maximum depth of a node is $\lg n$ and that the running time for the $\find$ method is $O(\lg n)$.
The second heuristic is called path compression and is implemented as part of the $\find$ method. Specifically, after finding the root of a tree, the $\find$ method makes a second pass over the path, redirecting all of the parent pointers along the path, so that they point directly to the root. This speeds up subsequent calls to $\find$ and ensures that any sequence of calls to $\find$ and $\merge$ takes essentially linear time. A detailed performance analysis is given in the following subsection. The core of the Javascript implementation is shown below.
Here's a script that demonstrates how the two heuristics combine to reduce the depth of the trees used to represent the sets.
let ms = new MergeSets();
ms.fromString('{o}');
ms.merge(1,2); ms.merge(3,4); ms.merge(5,6); ms.merge(7,8);
ms.merge(9,10); ms.merge(11,12); ms.merge(13,14);
console.log(ms.toString(0xe));
ms.merge(1,3); ms.merge(5,7); ms.merge(9,11); ms.merge(13,15);
console.log(ms.toString(0xe));
ms.merge(1,5); ms.merge(9,13); console.log(ms.toString(0xe));
ms.merge(1,9); console.log(ms.toString(0xe));
ms.find(4); ms.find(8); console.log(ms.toString(0xe));
ms.find(12); ms.find(15); console.log(ms.toString(0xe));
Here is the output produced when the script is run in the web app.
{a:1(b) c:1(d) e:1(f) g:1(h) i:1(j) k:1(l) m:1(n) o}
{a:2(b c:1(d)) e:2(f g:1(h)) i:2(j k:1(l)) m:1(n o)}
{a:3(b c:1(d) e:2(f g:1(h))) i:2(j k:1(l) m:1(n o))}
{a:3(b c:1(d) e:2(f g:1(h)) i:2(j k:1(l) m:1(n o)))}
{a:3(b c:1 d e:2(f) g:1 h i:2(j k:1(l) m:1(n o)))}
{a:3(b c:1 d e:2(f) g:1 h i:2(j) k:1 l m:1(n) o)}
Note that the $\toString()$ method is called with a format argument that causes it to show the implementation details (specifically, the structure of the trees and the non-zero ranks). In each tree, the children of a node are shown within a parenthesized list that immediately follows it. Without the format argument, only the sets represented by the trees are shown.

This implies that if a tree root has rank $k$, then $2^k \leq n$ and so $k \leq \lg n$. This implies an $O(\log n)$ bound on the time required for each find operation. Note that this result does not depend on the path compression heuristic. Also, note that some find operations can take time proportional to $\log n$, so there can be no better bound on the time for an arbitrary find operation. However, it is possible to get a stronger bound on a sequence of find operations, using a more sophisticated analysis that takes into account the effects of path compression.
Lemma 1. If $x$ is any node, $\rank(x) \leq rank(p(x))$ with the inequality strict if $p(x) \neq x$. The value of $\rank(x)$ is initially 0 and increases with time until $p(x)$ is assigned a value other than $x$. Subsequently, $\rank(x)$ does not change. The value of $\rank(p(x))$ is a nondecreasing function of time.
To facilitate the analysis, consider each find operation as consisting of a series of find steps, one for each node along the path followed by the operation. The objective is to put an upper bound on the total number of find steps. Note that the number of find steps at root nodes is equal to the number of find operations, so the remaining analysis considers only find steps at non-root nodes.
Define $\Delta(x)=rank(p(x)) - \rank(x)$ and note that $\Delta(x) \leq \lg n$ and that $\Delta(x)=0$ initially, and increases as $x$ acquires a parent and participates in find operations. Also, define a node $x$ to be dominant if $\Delta(x)>2\Delta(y)$ for all proper ancestors $y$ of $x$.
The analysis can be split into two cases, one covering find steps that occur at dominant nodes, and the other covering find steps that occur at non-dominant nodes. The analysis of the first case rests on the observation that there can be at most $\lg \lg n$ dominant nodes along the path from any node to the root of its tree. Consequently, each find operation can include at most $\lg \lg n$ find steps at dominant nodes. Consequently, in a sequence of $m$ find operations, at most $m\lg\lg n$ find steps occur at dominant nodes.
Proceeding to the second case, note that if $x$ is not dominant, then $x$ must have some proper ancestor $y$ with $\Delta(y) \geq \Delta(x)/2$. This implies that $\rank(p(y))-\rank(x) \geq 1.5 \times \Delta(x)$ before the find. After the find completes, $x$'s parent has rank at least as large the original value of $\rank(p(y))$. Consequently, the find operation causes $\Delta(x)$ to increase by a factor of at least 1.5. This is illustrated below.

Since every find step that occurs at $x$ at times when $x$ is not dominant causes $\Delta(x)$ to increase by a factor of 1.5, there can be no more than $2 \lg\lg n$ find steps at a node $x$ when it is not dominant. Consequently, the total number of find steps at non-dominant nodes is $O(n \log\log n)$ and the total number of find steps is $O((m+n)\log\log n)$.
Start by dividing the non-negative integers into a series of blocks by defining $block(0)=[0,1]$, $block(1)=[2,3]$, $block(2)=[4,5,6,7]$ and in general for $j\geq 1$, $block(j)=[2^j,\ldots,2^{j+1}-1]$. More simply, $block(j)$ can be written as the half-open interval $\left[2^j,2^{j+1}\right)$. A node $x$ is said to be on level 1 if there is some $block(j)$ that contains both $\rank(x)$ and $\rank(p(x))$. Any node that is not on level 1 is said to be on level 2. Note that once a node becomes a level 2 node, it can never again be a level 1 node (since $\rank(x)$ does not change once $x$ acquires a parent and $\rank(p(x))$ never decreases). In the example shown below, nodes $a$ and $d$ are on level 1, while nodes $b$ and $c$ are on level 2 A node is called singular if none of its proper ancestors is on the same level as it is. So in the example, $c$ and $d$ are singular.

As before, the analysis divides into two cases. The first counts the find steps that occur at singular nodes, while the second counts the find steps that occur at non-singular nodes. For the first case, note that any path from a node to the root of its tree can contain at most one singular node on each of the two levels. Hence, each find operation includes at most two find steps at singular nodes and the total number of find steps at singular nodes is $O(m)$.
The find steps at non-singular nodes can be divided into two sub-cases, one for the find steps involving level 1 nodes and another for the find steps involving level 2 nodes. Let's consider the second case first. Suppose $x$ is a non-singular node on level 2. Because $x$ is non-singular, it has some ancestor $y$ that is also on level 2. Because $x$ is on level 2, $\rank(p(x))$ is in a different block than $\rank(x)$. Similarly, $\rank(p(y))$ is in a different block than $\rank(y)$. Consequently, if $z$ is the root of the tree, then $\rank(z)$ is in a different block than $\rank(p(x))$. After the find, $z=p(x)$, so the find operation causes $\rank(p(x))$ to move into a different (and larger) block than it was in before the find. Since successive blocks double in size, this can happen at most $\lg \lg n$ times before $\rank(p(x))$ exceeds $\lg n$, so the number of find steps that can occur at node $x$ while $x$ is a non-singular node on level 2 is at most $\lg \lg n$. Hence, the total number of find steps that occur at non-singular nodes on level 2 is $O(n\log\log n)$.
This leaves the case of non-singular nodes on level 1. Let's suppose that $x$ is such a node and that $\block(j)$ is the subset of the integers that includes $\rank(x)$. A find involving $x$ will assign a new parent to $x$ causing $\rank(p(x))$ to increase by at least 1. Since $\block(j)$ contains $2^j$ values, this can happen no more than $2^j$ times while $x$ is on level 1. To bound the total number of find steps at non-singular level 1 nodes, the number of nodes in $block(j)$ must be bounded. This bound, can be obtained with the help of another lemma.
Lemma 2. For any integer $k>0$, the number of nodes of rank $k$ is at most $n/2^k$. Consequently, the number of nodes with rank $\geq k$ is less than $2n/2^k$.
Proof. Suppose that when a node $x$ is assigned a rank of $k$, all nodes in the tree with root $x$ are labeled $(x,k)$. By Lemma 1, at least $2^k$ nodes are labeled when $x$ receives a rank of $k$. If the root of the tree containing $x$ changes, the new root must have rank at least $k+1$, so no node is labeled more than once with a label of the form $(y,k)$ for a particular value of $k$. Since there are $n$ nodes, there are at most $n$ labels of the form $(y,k)$ for any particular $k$ and there are at least $2^k$ such labels for each node of rank $k$. Hence, at most $n/2^k$ nodes can be assigned a rank of $k$. Summing $n/2^j$ for all values of $j\geq k$ yields $2n/2^k$, so the number of nodes with rank $\geq k$ is at most $2n/2^k$. $\square$
Now, since a node with rank in $block(j)$ has rank at least $2^j$, the number of nodes in $block(j)$ is at most $2n/2^{2^j}$. Consequently, the number of find steps that occur at non-singular nodes on level 1 with rank in $block(j)$ is at most $2^{j} \left( 2n/2^{2^j} \right)$. There are no non-singular nodes with rank in $\block(0)$, so summing this expression over all values of $j > 0$ yields $$ 2n\sum_{j>0} 2^j/{2^{2^j}} \leq 2n\sum_{j>0} j/{2^j} \leq 4n $$ The first inequality above holds because every term in the summation on the left-hand side is also present in the summation on the right-hand side (along with many additional terms). The second inequality follows directly from the formula for an unbounded arithmetic-geometric series. Hence, the number of find steps at non-singular nodes on level 1 is $O(n)$. Combining this with the results from the other cases, the total number of find steps is $O(m+n\log\log n)$. Note that for $m\geq n\lg\lg n$, the number of find steps is $O(m)$, so it's only possible to improve the analysis when $m< n\lg\lg n$.
Before proceeding further, let's recap. In the analysis just completed, the find steps were divided into three categories.
Now, a node $x$ is defined to be on level 1 if there is an interval defined by $\block_1$ that contains both $\rank(x)$ and $\rank(p(x))$. Node $x$ is defined to be on level 2 if it is not on level 1 and there is an interval defined by $\block_2$ that contains both $\rank(x)$ and $\rank(p(x))$. Nodes that are on neither level 1 nor level 2 are on level 3. So, in the example below, nodes $a$ and $d$ are on level 1, $b$ is on level 2 and $c$ is on level 3. As before, a node is called singular if none of its ancestors is on the same level that it is. So, in the example, nodes $b$, $c$ and $d$ are singular.

As before, a case analysis is used, but now there are four cases to consider.

Since the number of nodes with rank in $block_2(j)$ is $\leq 2n/2^{2^{[j]}} = 2n/2^{[j+1]}$ for $j>0$, the number of find steps at non-singular nodes on level 2 is at most $2^{[j]} \left( 2n/2^{[j+1]} \right)$ for $j>0$. There can be no non-singular nodes on level 2 with rank in $\block_2(0)$, so, the total number of find steps that occur at non-singular nodes on level 2 is at most $$ 2n\sum_{j>0} 2^{[j]}/{2^{2^{[j]}}} \leq 2n\sum_{j>0} j/2^j \leq 4n $$ That leaves just the fourth case. Let $x$ be a non-singular node with $\rank(x)$ in $\block_2(j)$. Because $x$ is on level 3, its parent's rank is in a different level 2 interval than its rank. Because it is non-singular, it has a proper ancestor $y$ that is also on level 3. Consequently, the root of the tree has a rank that is in a different level 2 interval than $\rank(p(x))$. This means that a find involving $x$ causes $\rank(p(x))$ to move to a different level 2 interval. Consequently, the number of find steps that can occur at $x$ while it is non-singular and on level 3 is bounded by the number of level 2 intervals that include values $\leq \lg n$. If $\beta(n)$ is defined to be the smallest integer $i>0$ for which $2^{[i]}> \lg n$, then the number of level 2 intervals that includes values $\leq \lg n$ is $\beta (n)$ and the number of find steps at any non-singular node on level 3 is at most $\beta(n)$. The function $\beta(n)$ grows extremely slowly with $n$; in general $\beta(2^{[k]})=k$.
Putting together the results from the four cases above, the total number of find steps is $O(m + n\beta(n))$. Observe now that with this analysis, the number of find steps is $O(m)$ whenever $m \geq n\beta(n)$, so the analysis can be improved only for $m < n\beta(n)$. This can be done by further sub-dividing the fourth case.
As before, the non-root nodes are assigned to levels. Specifically, a node $x$ is defined to be on level 1 if $\rank(x)$ and $\rank(p(x))$ are both in some interval defined by $block_1)$. For $1 < i\leq \alpha(m,n)+1$, $x$ is defined to be on level $i$ if it is not on level $i-1$ and there is some interval defined by $block_i$ that contains both $\rank(x)$ and $\rank(p(x))$. Node $x$ is called singular if it has no proper ancestor on the same level as $x$.
As before, the analysis can be broken down into cases.

Since the number of nodes with rank in $block_i(j)$ is $\leq 2n/2^{A_i(j)}$, the number of find steps experienced by non-singular nodes on level $i$ whose rank is in $\block_i(j)$ is at most $A_i(j) \left( 2n/2^{A_i(j)}\right)$ for $j>0$. There are no non-singular nodes with rank in $\block_i(0)$ for all $i$, so the total number of find steps experienced by non-singular nodes on levels 2 through $\alpha(m,n)$ is at most \begin{eqnarray*} 2n \sum_{2\leq i \leq \alpha(m,n)} \sum_{j>0} A_i(j)/2^{A_i(j)} &\leq& 2n \sum_{2\leq i \leq \alpha(m,n)} \sum_{j>0} j/2^j \\ &\leq& 2(\alpha(m,n)-1)n \sum_{j>0} j/2^j \\ &\leq& 4(\alpha(m,n)-1) n \end{eqnarray*} Combining the bounds in the four cases gives $O((m+n)\alpha(m,n))$ for a sequence of $m$ find operations.
To compare this result with the previous one,
one must compare the growth rates of $\alpha$ and $\beta$.
Note that $\alpha$ grows most quickly when $m\leq n$.
In this case,
$\alpha(m,n)=\alpha(n,n)=\min \{i\geq 1 | A_i(1)>\lg n\}$.
For the smallest values of $n$, $\alpha(n,n)$ and $\beta(n)$
remain fairly close, but while $\beta(2^{[5]})=5$,
$\alpha(n)$ does not become 5 until $n$ reaches $2^{[65537]}$.
By that point, $\beta(n)=65537$ and from there,
$\beta$ continues to grow much faster than $\alpha$.
Finally, it's worth noting that for $m\geq n \beta(n)$, $\alpha(m,n) \leq 2$.
So, this is analysis is consistent with the previous analysis when
$m\geq n \beta(n)$.
Scanner
The $\Scanner$ class is a utility class used by the various
data structure modules to implement their $\fromString$ methods.
It is initialized with a string and
provides a variety of helper methods for incrementally parsing that string.
It maintains a cursor that defines the current position
in the string; the cursor is updated as portions of the string are parsed.
The most commonly used methods are listed below.
'c:5' might represent an item $c$
with some associated numerical property.
"[ a b 5 )", then
nextIndexList('[',')')
returns the array [1,2,5].
The individual index values in the list are parsed using
$\nextIndex$ and the optional argument $\prop(i)$
is passed to $\nextIndex$. This allows one to use
$\nextIndexList$ to parse strings like
"[1:3 e:2 c:1]", for example.
If a valid list is found, it is returned as an array and the
cursor is advanced.
Otherwise, null is returned and
the cursor is left unchanged.