\( \newcommand{\Top}{\textit{Top}} \newcommand{\List}{\textit{list}} \newcommand{\ListPair}{\textit{list pair}} \newcommand{\ListSet}{\textit{list set}} \newcommand{\ReverseLists}{\textit{reversible lists}} \newcommand{\MergeSets}{\textit{merge sets}} \newcommand{\Scanner}{\textit{scanner}} \newcommand{\constructor}{\textit{constructor}} \newcommand{\Graph}{\textit{graph}} \newcommand{\this}{\textit{this}} \newcommand{\true}{\textit{true}} \newcommand{\gn}{\textit{g.n}} \newcommand{\gm}{\textit{g.m}} \newcommand{\valid}{\textit{valid}} \newcommand{\reset}{\textit{reset}} \newcommand{\expand}{\textit{expand}} \newcommand{\equals}{\textit{equals}} \newcommand{\indexTstring}{\textit{index2string}} \newcommand{\xTs}{\textit{x2s}} \newcommand{\ilistTstring}{\textit{ilist2string}} \newcommand{\toString}{\textit{toString}} \newcommand{\fromString}{\textit{fromString}} \newcommand{\assign}{\textit{assign}} \newcommand{\xfer}{\textit{xfer}} \newcommand{\clear}{\textit{clear}} \newcommand{\getStats}{\textit{getStats}} \newcommand{\clearStats}{\textit{clearStats}} \newcommand{\first}{\textit{first}} \newcommand{\last}{\textit{last}} \newcommand{\next}{\textit{next}} \newcommand{\length}{\textit{length}} \newcommand{\empty}{\textit{empty}} \newcommand{\at}{\textit{at}} \newcommand{\contains}{\textit{contains}} \newcommand{\insert}{\textit{insert}} \newcommand{\push}{\textit{push}} \newcommand{\pop}{\textit{pop}} \newcommand{\top}{\textit{top}} \newcommand{\enq}{\textit{enq}} \newcommand{\deq}{\textit{deq}} \newcommand{\setEquals}{\textit{setEquals}} \newcommand{\prev}{\textit{prev}} \newcommand{\delete}{\textit{delete}} \newcommand{\deleteNext}{\textit{deleteNext}} \newcommand{\popLast}{\textit{popLast}} \newcommand{\value}{\textit{value}} \newcommand{\val}{\textit{val}} \newcommand{\hasValues}{\textit{hasValues}} \newcommand{\hasReverse}{\textit{hasReverse}} \newcommand{\in}{\textit{in}} \newcommand{\swap}{\textit{swap}} \newcommand{\isFirst}{\textit{isFirst}} \newcommand{\singleton}{\textit{singleton}} \newcommand{\findList}{\textit{findList}} \newcommand{\rotate}{\textit{rotate}} \newcommand{\join}{\textit{join}} \newcommand{\sort}{\textit{sort}} \newcommand{\reverse}{\textit{reverse}} \newcommand{\find}{\textit{find}} \newcommand{\merge}{\textit{merge}} \newcommand{\rank}{\textit{rank}} \newcommand{\cursor}{\textit{cursor}} \newcommand{\firstNonSpace}{\textit{firstNonSpace}} \newcommand{\skipspace}{\textit{skipspace}} \newcommand{\isdigit}{\textit{isdigit}} \newcommand{\islower}{\textit{islower}} \newcommand{\isupper}{\textit{isupper}} \newcommand{\verify}{\textit{verify}} \newcommand{\nextInt}{\textit{nextInt}} \newcommand{\nextNumber}{\textit{nextNumber}} \newcommand{\nextWord}{\textit{nextWord}} \newcommand{\nextLine}{\textit{nextLine}} \newcommand{\nextIndex}{\textit{nextIndex}} \newcommand{\nextIndexList}{\textit{nextIndexList}} \newcommand{\nabor}{\textit{nabor}} \newcommand{\components}{\textit{components}} \newcommand{\comps}{\textit{comps}} \newcommand{\firstAt}{\textit{firstAt}} \newcommand{\nextAt}{\textit{nextAt}} \newcommand{\run}{\textit{run}} \newcommand{\matches}{\textit{matches}} \newcommand{\nan}{\texttt{NaN}} \newcommand{\mate}{\textit{mate}} \newcommand{\other}{\textit{other}} \newcommand{\label}{\textit{label}} \newcommand{\prop}{\textit{prop}} \newcommand{\skip}{\textit{skip}} \newcommand{\compare}{\textit{compare}} \newcommand{\block}{\textit{block}} \)

Basic Data Structures©

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

Introduction

Many of the algorithms described here require multiple data structures that address different aspects of the problem being solved. Because the data structures are closely related, there must be a way to maintain correspondences among them. One simple way to do this is with index-based data structures. Here is an example of an index-based list used to represent the list of distinct integers $[7,5,3,8,2]$. In general, an index list can be used to represent any list of distinct positive integers within a bounded range, in this case, 1 to 10.


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/js
The provided code is also available as part of the Grafalgo library, which can be downloaded from
https://github.com/jonturner53/grafalgo
The 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.

Common Methods

All the provided data structures have a common super-class $\Top$, which defines an index range $1\ldots n$ for some integer $n$ and provides the methods listed below. Most classes also define the following methods.

List

The $\List$ class defines a list of distinct integers in a limited range $1\ldots n$ and supports the following methods. When first constructed, a $\List$ uses a single $\next$ array, linking successive list items; items not on the list have $\next$ values of $-1$, enabling a constant time membership test. A $\List$ $l$ can be extended dynamically to include links in the reverse direction, by simply using a method that requires reverse links. These include

The $\List$ object can also be extended to associate a set of values with the list items. This enables the following method.

The assigned values are often simply numbers, but may be strings, arrays or objects. This extension can be enabled implicitly, by setting the value of an item using the $\value()$ method. The core methods for the $\List$ class are shown below.

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. $\ListPair$ implements both lists using shared $\next$ and $\prev$ arrays. For items in list 2, the stored $\prev$ values are negative integers. All operations listed above take constant time. The core methods for the $\ListPair$ class are shown below.

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. $\ListSet$ is implemented using shared $\next$ and $\prev$ arrays. The $\findList(i)$ method takes time proportional to the position of item $i$ in the list and the $\sort$ method takes $O(n \log n)$ time. All others listed above take constant time. The core methods for the $\ListSet$ class are shown 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.

In the $\ReverseLists$ data structure, the $\next$ and $\prev$ arrays of the $\ListSet$ class, are replaced with arrays that represent neighboring list items, $\nabor\texttt{1}$ and $\nabor\texttt{2}$. A list is reversed by effectively complementing a bit that determines which of two neighbors of the first item is the next item on the list and which is the last item. With this information, one can traverse the list in either direction using a “trailing pointer.” In the Javascript implementation, the first list item uses a positive value for the neighbor that identifies the next list item and a negative value for the other neighbor. The implementations of the key methods are shown 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. Each subset in the $\MergeSets$ object is implemented as a tree, defined using parent pointers. That is, $p(i)$ identifies the parent of $i$ in its tree and the root of the tree serves as its identifier. If $i$ is a root, $p(i)=i$. This is illustrated 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.

Performance Analysis

(The analysis in this section is an expanded version of the analysis in Chapter 2 of [Tarjan87].) Although the $\MergeSets$ data structure is very simple, fully analyzing its performance is not. To make it easier to understand, the analysis is presented in several steps, with each successive step giving a tighter bound on the performance.

Basic Analysis

The initialization of the data structure takes $O(n)$ time and the merge operation takes constant time. So, the only question is how much time is required for the find operations? This depends on the depth of the tree. We start by noting that the merge-by-rank heuristic ensures that the rank of any item is strictly less than the rank of its parent. Consequently, $\rank(x)$ is an upper bound on the height of $x$ in the tree. So, if $x$ is a tree root, the time for a find operation starting within $x$'s tree is at most $\rank(x)$. So, an upper bound on $\rank(x)$, yields a bound on the running time of the find operation. The key to bounding $\rank(x)$ is to observe that the number of nodes in $x$'s subtree is at least $2^{\rank(x)}$. This can be proved by induction on the number of merge operations, as illustrated below.


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.

A Better Analysis

As a first step in a more detailed analysis, let's make a few observations about the ranks. First, as noted earlier, the rank of a non-root node is strictly less than the rank of its parent. Also, the rank of a node can increase as a result of merge operations, but it can never decrease, and once a node becomes a child of another node, its rank can no longer change. Finally, $\rank(p(x))$ can increase (as a result of either merge operations or find operations that change $p(x)$), but it can never decrease. These observations are collected in the following lemma.

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)$.

A Still Better Analysis

From a practical perspective, there is little reason to carry the analysis further, since for any practical value of $n$, $\lg \lg n$ is very small. However, it is possible to do better and it's instructive to see how. The new analysis requires some additional technical machinery. Rather than go straight to the final analysis, let's build up to it in several steps, with each step providing some improvement on what has gone before. The first step will show that the number of find steps is at $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.

To improve on this result, a better bound on the number of find steps in the last category is needed.

An Even Better (but not quite best) Analysis

The analysis from the last section can be improved by dividing the case of non-singular nodes on level 2 into two sub-cases. First let's define a second, coarser partition on the integers, by letting \begin{eqnarray*} \block_2(0)&=&[0,4) \\ \block_2(1)&=&[4,16)=\left[2^2,2^{2^2}\right) \\ \block_2(2)&=&[16,65536]=\left[2^{2^2},2^{2^{2^2}}\right) \end{eqnarray*} and in general $$ \block_2(j)=\left[2^{[j]},2^{[j+1]}\right) $$ where $2^{[1]}=2^2$ and $2^{[j]}=2^{2^{[j-1]}}$ for $j>1$. For notational consistency, let $\block_1(j)$ denote the original partition of the integers.

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.

Let's proceed with the analysis of the third case. Let $x$ be a non-singular node with $\rank(x)$ in $\block_2(j)$. Because $x$ is on level 2, its parent's rank is in a different level 1 interval than its rank. Because it is non-singular, it has a proper ancestor $y$ that is also on level 2. Consequently, the root of the tree has rank that is in a different level 1 interval than $\rank(p(x))$. This means that a find involving $x$ causes $\rank(p(x))$ to move to a different level 1 interval. Hence, the number of find steps that occur at $x$ while it is non-singular and on level 2 is less than the number of level 1 intervals that intersect $block_2(j)$, and this at most $2^{[j]}-2^{[j-1]}<2^{[j]}$, as illustrated below.


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.

The Final Analysis

The key to this final analysis is to allow the number of distinct cases to grow further. This can be done by defining a series of partitions on the integers, $block_1$, $block_2$, $block_3$ and so forth, with each partition coarser than the previous one, and with the last partition requiring just a single interval to span the range up to $\lg n$. Specifically, for $i>0$, $\block_i(0)$ starts at 0 and for all $j>0$, $\block_i(j)$ starts with $A_i(j)$, where $A$ is Ackerman's function and is defined as follows. $$ A_i(j) = \left\{ \begin{array}{ll} 2^j & \textrm{for $i=1$, $j\geq 1$} \\ A_{i-1}(2) & \textrm{for $i>1$, $j=1$} \\ A_{i-1}(A_i(j-1)) & \textrm{for $i,j>1$} \end{array} \right. $$ It can be helpful to think of Ackerman's function as a family of related functions $A_i$. The notation used here was chosen to emphasize that viewpoint. Notice that with this definition, $A_2(j)=2^{[j]}$ for all $j\geq 1$. Consequently this definition of the blocks is consistent with the earlier definitions of $\block_1$ and $\block_2$. Now, define a functional inverse $\alpha$ of Ackerman's function. $$ \alpha(m,n)=\min \{i\geq 1 | A_i(\lceil m/n \rceil)>\lg n\} $$ This means that, $A_{\alpha(m,n)}$ defines at most $\lceil m/n \rceil$ intervals that contain values $\leq \lg n$. The definition of $\block_{\alpha(m,n)}$ is simplified to include just a single interval $[0,\ldots,\lfloor \lg n \rfloor]$.

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.

Proceeding with the analysis of the third case, let $x$ be a non-singular node on level $i$ ($1 < i\leq \alpha(m,n)$) and assume that $\block_i(j)$ includes $\rank(x)$. Because $x$ is on level $i$, its parent's rank is in a different interval on level $i-1$ than its rank. Because it is non-singular, it has a proper ancestor $y$ that is also on level $i$. Consequently, the root of the tree has rank that is in a different interval on level $i-1$ than $\rank(p(x))$. Hence, a find involving $x$ causes $\rank(p(x))$ to move to a different interval on level $i-1$. This means that the number of find steps that $x$ can experience while it is non-singular and on level $i$ is bounded by the number of intervals on level $i-1$ that intersect $\block_i(j)$. Call this number $b_i(j)$ and note that $b_i(0)=2$ for all $i$ and that for $j>0$, $b_i(j) \leq A_i(j)-A_i(j-1)< A_i(j)$, as illustrated below.


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.

References

[Tarjan87]
Tarjan, R. E., Network Algorithms and Data Structures. Society for Industrial and Applied Mathematics, 1987.

© Jonathan Turner - 2022