Mark Nelson

Programming, mostly.

  • Home
  • About Mark Nelson
  • Archives
  • Liberal Code Use Policy

Fast String Searching With Suffix Trees


« Priority Queues and the STL Data Compression with the Burrows-Wheeler Transform »

Posted in August 1st, 1996 by Mark in Computer Science, Data Compression, Magazine Articles

Published in Dr. Dobb's Journal August, 1996

I think that I shall never see
A poem lovely as a tree.
Poems are made by fools like me,
But only God can make a tree.

- Joyce Kilmer

A tree's a tree. How many more do you need to look at?
-Ronald Reagan


The problem

Matching string sequences is a problem that computer programmers face on a regular basis. Some programming tasks, such as data compression or DNA sequencing, can benefit enormously from improvements in string matching algorithms. This article discusses a relatively unknown data structure, the suffix tree, and shows how its characteristics can be used to attack difficult string matching problems.

Imagine that you've just been hired as a programmer working on a DNA sequencing project. Researchers are busy slicing and dicing viral genetic material, producing fragmented sequences of nucleotides. They send these sequences to your server, which is then expected to locate the sequences in a database of genomes. The genome for a given virus can have hundreds of thousands of nucleotide bases, and you have hundreds of viruses in your database. You are expected to implement this as a client/server project that gives real-time feedback to the impatient Ph.D.s. What's the best way to go about it?

It is obvious at this point that a brute force string search is going to be terribly inefficient. This type of search would require you to perform a string comparison at every single nucleotide in every genome in your database. Testing a long fragment that has a high hit rate of partial matches would make your client/server system look like an antique batch processing machine. Your challenge is to come up with an efficient string matching solution.

The intuitive solution

Since the database that you are testing against is invariant, preprocessing it to simplify the search seems like a good idea. One preprocessing approach is to build a search trie. For searching through input text, a straightforward approach to a search trie yields a thing called a suffix trie. (The suffix trie is just one step away from my final destination, the suffix tree.) A trie is a type of tree that has N possible branches from each node, where N is the number of characters in the alphabet. The word 'suffix' is used in this case to refer to the fact that the trie contains all of the suffixes of a given block of text (perhaps a viral genome.)



Figure 1
The Suffix Trie Representing "BANANAS"

Figure 1 shows a Suffix trie for the word BANANAS. There are two important facts to note about this trie. First, starting at the root node, each of the suffixes of BANANAS is found in the trie, starting with BANANAS, ANANAS, NANAS, and finishing up with a solitary S. Second, because of this organization, you can search for any substring of the word by starting at the root and following matches down the tree until exhausted.

The second point is what makes the suffix trie such a nice construct. If you have a input text of length N, and a search string of length M, a traiditonal brute force search will take as many as N*M character comparison to complete. Optimized searching techniques, such as the Boyer-Moore algorithm can guarantee searches that require no more than M+N comparisons, with even better average performance. But the suffix trie demolishes this performance by requiring just M character comparisons, regardless of the length of the text being searched!

Remarkable as this might seem, it means I could determine if the word BANANAS was in the collected works of William Shakespeare by performing just seven character comparisons. Of course, there is just one little catch: the time needed to construct the trie.

The reason you don't hear much about the use of suffix tries is the simple fact that constructing one requires O(N2) time and space. This quadratic performance rules out the use of suffix tries where they are needed most: to search through long blocks of data.

Under the spreading suffix tree

A reasonable way past this dilemma was proposed by Edward McCreight in 1976, when he published his paper on what came to be known as the suffix tree. The suffix tree for a given block of data retains the same topology as the suffix trie, but it eliminates nodes that have only a single descendant. This process, known as path compression, means that individual edges in the tree now may represent sequences of text instead of single characters.



Figure 2
The Suffix Trie Representing "BANANAS"

Figure 2 shows what the suffix trie from Figure 1 looks like when converted to a suffix tree. You can see that the tree still has the same general shape, just far fewer nodes. By eliminating every node with just a single descendant, the count is reduced from 23 to 11.

In fact, the reduction in the number of nodes is such that the time and space requirements for constructing a suffix tree are reduced from O(N2) to O(N). In the worst case, a suffix tree can be built with a maximum of 2N nodes, where N is the length of the input text. So for a one-time investment proportional to the length of the input text, we can create a tree that turbocharges our string searches.

Even you can make a tree

McCreight's original algorithm for constructing a suffix tree had a few disadvantages. Principle among them was the requirement that the tree be built in reverse order, meaning characters were added from the end of the input. This ruled the algorithm out for on line processing, making it much more difficult to use for applications such as data compression.

Twenty years later, Esko Ukkonen from the University of Helsinki came to the rescue with a slightly modified version of the algorithm that works from left to right. Both my sample code and the descriptions that follow are based on Ukkonen's work, published in the September 1995 issue of Algorithmica.

For a given string of text, T, Ukkonen's algorithm starts with an empty tree, then progressively adds each of the N prefixes of T to the suffix tree. For example, when creating the suffix tree for BANANAS, B is inserted into the tree, then BA, then BAN, and so on. When BANANAS is finally inserted, the tree is complete.



Figure 3
Progressively Building the Suffix Tree

Suffix tree mechanics

Adding a new prefix to the tree is done by walking through the tree and visiting each of the suffixes of the current tree. We start at the longest suffix (BAN in Figure 3), and work our way down to the shortest suffix, which is the empty string. Each suffix ends at a node that consists of one of these three types:

  • A leaf node. In Figure 4, the nodes labeled 1,2, 4, and 5 are leaf nodes.
  • An explicit node. The non-leaf nodes that are labeled 0 and 3 in Figure 4 are explicit nodes. They represent a point on the tree where two or more edges part ways.
  • An implicit node. In Figure 4, prefixes such as BO, BOO, and OO all end in the middle of an edge. These positions are referred to as implicit nodes. They would represent nodes in the suffix trie, but path compression eliminated them. As the tree is built, implicit nodes are sometimes converted to explicit nodes.



Figure 4
BOOKKEEPER after adding BOOK

In Figure 4, there are five suffixes in the tree (including the empty string) after adding BOOK to the structure. Adding the next prefix, BOOKK to the tree means visiting each of the suffixes in the existing tree, and adding letter K to the end of the suffix.

The first four suffixes, BOOK, OOK, OK, and K, all end at leaf nodes. Because of the path compression applied to suffix trees, adding a new character to a leaf node will always just add to the string on that node. It will never create a new node, regardless of the letter being added.

After all of the leaf nodes have been updated, we still need to add character 'K' to the empty string, which is found at node 0. Since there is already an edge leaving node 0 that starts with letter K, we don't have to do anything. The newly added suffix K will be found at node 0, and will end at the implicit node found one character down along the edge leading to node 2.

The final shape of the resulting tree is shown in Figure 5.



Figure 5
The same tree after adding BOOKK

Things get knotty

Updating the tree in Figure 4 was relatively easy. We performed two types of updates: the first was simply the extension of an edge, and the second was an implicit update, which involved no work at all. Adding BOOKKE to the tree shown in Figure 5 will demonstrate the two other types of updates. In the first type, a new node is created to split an existing edge at an implicit node, followed by the addition of a new edge. The second type of update consists of adding a new edge to an explicit node.



Figure 6
The Split and Add Update

When adding BOOKKE to the tree in Figure 5, we once again start with the longest suffix, BOOKK, and work our way to the shortest, the empty string. Updating the longer suffixes is trivial as long as we are updating leaf nodes. In Figure 5, the suffixes that end in leaf nodes are BOOKK, OOKK, OKK, and KK. The first tree in Figure 6 shows what the tree looks like after these suffixes have been updated using the simple string extension.

The first suffix in Figure 5 that doesn't terminate at a leaf node is K. When updating a suffix tree, the first non-leaf node is defined as the active point of the tree. All of the suffixes that are longer than the suffix defined by the active point will end in leaf nodes. None of the suffixes after this point will terminate in leaf nodes.

The suffix K terminates in an implicit node part way down the edge defined by KKE. When testing non-leaf nodes, we need to see if they have any descendants that match the new character being appended. In this case, that would be E.

A quick look at the first K in KKE shows that it only has a single descendant: K. So this means we have to add a descendent to represent Letter E. This is a two step process. First, we split the edge holding the arc so that it has an explicit node at the end of the suffix being tested. The middle tree in Figure 6 shows what the tree looks like after the split.

Once the edge has been split, and the new node has been added, you have a tree that looks like that in the third position of Figure 6. Note that the K node, which has now grown to be KE, has become a leaf node.

Updating an explicit node

After updating suffix K, we still have to update the next shorter suffix, which is the empty string. The empty string ends at explicit node 0, so we just have to check to see if it has a descendant that starts with letter E. A quick look at the tree in Figure 6 shows that node 0 doesn't have a descendant, so another leaf node is added, which yields the tree shown in Figure 7.



Figure 7

Generalizing the algorithm

By taking advantage of a few of the characteristics of the suffix tree, we can generate a fairly efficient algorithm. The first important trait is this: once a leaf node, always a leaf node. Any node that we create as a leaf will never be given a descendant, it will only be extended through character concatenation. More importantly, every time we add a new suffix to the tree, we are going to automatically extend the edges leading into every leaf node by a single character. That character will be the last character in the new suffix.

This makes management of the edges leading into leaf nodes easy. Any time we create a new leaf node, we automatically set its edge to represent all the characters from its starting point to the end of the input text. Even if we don't know what those characters are, we know they will be added to the tree eventually. Because of this, once a leaf node is created, we can just forget about it! If the edge is split, its starting point may change, but it will still extend all the way to the end of the input text.

This means that we only have to worry about updating explicit and implicit nodes at the active point, which was the first non-leaf node. Given this, we would have to progress from the active point to the empty string, testing each node for update eligibility.

However, we can save some time by stopping our update earlier. As we walk through the suffixes, we will add a new edge to each node that doesn't have a descendant edge starting with the correct character. When we finally do reach a node that has the correct character as a descendant, we can simply stop updating. Knowing how the construction algorithm works, you can see that if you find a certain character as a descendant of a particular suffix, you are bound to also find it as a descendant of every smaller suffix.

The point where you find the first matching descendant is called the end point. The end point has an additional feature that makes it particularly useful. Since we were adding leaves to every suffix between the active point and the end point, we now know that every suffix longer than the end point is a leaf node. This means the end point will turn into the active point on the next pass over the tree!

By confining our updates to the suffixes between the active point and the end point, we cut way back on the processing required to update the tree. And by keeping track of the end point, we automatically know what the active point will be on the next pass. A first pass at the update algorithm using this information might look something like this (in C-like pseudo code) :

PLAIN TEXT C:
  1. Update ( new_suffix )
  2. {
  3.   current_suffix = active_point
  4.   test_char = last_char in new_suffix
  5.   done = false;
  6.   while ( !done ) {
  7.     if current_suffix ends at an explicit node {
  8.       if the node has no descendant edge starting with test_char
  9.         create new leaf edge starting at the explicit node
  10.       else
  11.         done = true;
  12.     } else {
  13.       if the implicit node 's next char isn't test_char {
  14.         split the edge at the implicit node
  15.         create new leaf edge starting at the split in the edge
  16.       } else
  17.         done = true;
  18.     }
  19.     if current_suffix is the empty string
  20.       done = true;
  21.     else
  22.        current_suffix = next_smaller_suffix ( current_suffix )
  23.   }
  24.   active_point = current_suffix
  25. }

The Suffix Pointer

The pseudo-code algorithm shown above is more or less accurate, but it glosses over one difficulty. As we are navigating through the tree, we move to the next smaller suffix via a call to next_smaller_suffix(). This routine has to find the implicit or explicit node corresponding to a particular suffix.

If we do this by simply walking down the tree until we find the correct node, our algorithm isn't going to run in linear time. To get around this, we have to add one additional pointer to the tree: the suffix pointer. The suffix pointer is a pointer found at each internal node. Each internal node represents a sequence of characters that start at the root. The suffix pointer points to the node that is the first suffix of that string. So if a particular string contains characters 0 through N of the input text, the suffix pointer for that string will point to the node that is the termination point for the string starting at the root that represents characters 1 through N of the input text.

Figure 8 shows the suffix tree for the string ABABABC. The first suffix pointer is found at the node that represents ABAB. The first suffix of that string would be BAB, and that is where the suffix pointer at ABAB points. Likewise, BAB has its own suffix pointer, which points to the node for AB.



Figure 7
The suffix tree for ABABABC with suffix pointers shown as dashed lines

The suffix pointers are built at the same time the update to the tree is taking place. As I move from the active point to the end point, I keep track of the parent node of each of the new leaves I create. Each time I create a new edge, I also create a suffix pointer from the parent node of the last leaf edge I created to the current parent edge. (Obviously, I can't do this for the first edge created in the update, but I do for all the remaining edges.)

With the suffix pointers in place, navigating from one suffix to the next is simply a matter of following a pointer. This critical addition to the algorithm is what reduces it to an O(N) algorithm.

Tree houses

To help illustrate this article, I wrote a short program, STREE.CPP, that reads in a string of text from standard input and builds a suffix tree using fully documented C++. A second version, STREED.CPP, has extensive debug output as well. Links to both are available at the bottom of this article.

Understanding STREE.CPP is really just a matter of understanding the workings of the data structures that it contains. The most important data structure is the Edge object. The class definition for Edge is:

PLAIN TEXT C++:
  1. class Edge {
  2.     public :
  3.         int first_char_index;
  4.         int last_char_index;
  5.         int end_node;
  6.         int start_node;
  7.         void Insert ( );
  8.         void Remove ( );
  9.         Edge ( );
  10.         Edge ( int init_first_char_index,
  11.               int init_last_char_index,
  12.               int parent_node );
  13.         int SplitEdge ( Suffix &s );
  14.         static Edge Find ( int node, int c );
  15.         static int Hash ( int node, int c );
  16. };

Each time a new edge in the suffix tree is created, a new Edge object is created to represent it. The four data members of the object are defined as follows:

first_char_index, last_char_index:
Each of the edges in the tree has a sequence of characters from the input text associated with it. To ensure that the storage size of each edge is identical, we just store two indices into the input text to represent the sequence.
start_node:
The number of the node that represents the starting node for this edge. Node 0 is the root of the tree.
end_node:
The number of the node that represents the end node for this edge. Each time an edge is created, a new end node is created as well. The end node for every edge will not change over the life of the tree, so this can be used as an edge id as well.

One of the most frequent tasks performed when building the suffix tree is to search for the edge emanating from a particular node based on the first character in its sequence. On a byte oriented computer, there could be as many as 256 edges originating at a single node. To make the search reasonably quick and easy, I store the edges in a hash table, using a hash key based on their starting node number and the first character of their substring. The Insert() and Remove() member functions are used to manage the transfer of edges in and out of the hash table.

The second important data structure used when building the suffix tree is the Suffix object. Remember that updating the tree is done by working through all of the suffixes of the string currently stored in the tree, starting with the longest, and ending at the end point. A Suffix is simply a sequence of characters that starts at node 0 and ends at some point in the tree.

It makes sense that we can then safely represent any suffix by defining just the position in the tree of its last character, since we know the first character starts at node 0, the root. The Suffix object, whose definition is shown here, defines a given suffix using that system:

PLAIN TEXT C++:
  1. class Suffix {
  2.     public :
  3.         int origin_node;
  4.         int first_char_index;
  5.         int last_char_index;
  6.         Suffix ( int node, int start, int stop );
  7.         int Explicit ( );
  8.         int Implicit ( );
  9.         void Canonize ( );
  10. };

The Suffix object defines the last character in a string by starting at a specific node, then following the string of characters in the input sequence pointed to by the first_char_index and last_char_index members. For example, in Figure 8, the longest suffix "ABABABC" would have an origin_node of 0, a first_char_index of 0, and a last_char_index of 6.

Ukkonen's algorithm requires that we work with these Suffix definitions in canonical form. The Canonize() function is called to perform this transformation any time a Suffix object is modified. The canonical representation of the suffix simply requires that the origin_node in the Suffix object be the closest parent to the end point of the string. This means that the suffix string represented by the pair (0, "ABABABC"), would be canonized by moving first to (1, "ABABC"), then (4, "ABC"), and finally (8,"").

When a suffix string ends on an explicit node, the canonical representation will use an empty string to define the remaining characters in the string. An empty string is defined by setting first_char_index to be greater than last_char_index. When this is the case, we know that the suffix ends on an explicit node. If first_char_index is less than or equal to last_char_index, it means that the suffix string ends on an implicit node.

Given these data structure definitions, I think you will find the code in STREE.CPP to be a straightforward implementation of the Ukkonen algorithm. For additional clarity, use STREED.CPP to dump copious debug information out at runtime.

Acknowledgments

I was finally convinced to tackle suffix tree construction by reading Jesper Larsson's paper for the 1996 IEEE Data Compression Conference. Jesper was also kind enough to provide me with sample code and pointers to Ukkonen's paper.

References

E.M. McCreight. A space-economical suffix tree construction algorithm. Journal of the ACM, 23:262-272, 1976.

E. Ukkonen. On-line construction of suffix trees. Algorithmica, 14(3):249-260, September 1995.

Source Code

Good news - this source code has been updated. It was originally published in 1996, pre-standard, and needed just a few nips and tucks to work properly in today's world. These new versions of the code should be pretty portable - the build properly with g++ 3.x, 4.x and Visual C++ 2003.

stree2006.cpp
A simple program that builds a suffix tree from an input string.
streed2006.cpp
The same program with much debugging code added.

The original code is her for the curious, but should not be used:

stree.cpp
A simple program that builds a suffix tree from an input string.
streed.cpp
The same program with much debugging code added.

66 users commented in " Fast String Searching With Suffix Trees "

Follow-up comment rss or Leave a Trackback Martin said, in December 5th, 2006 at 3:01 am

Nice paper but there is room for improvement.

1) Do use the same example throughout the text instead of using different more or less suited examples to illustrate different points - thus making it hard to follow what is going on. MISSISSIPPI would make a excellent example string.

2) Figure 4 already contains an explicit update which is not explained before carrying on - that is rather confusing.

Mark said, in December 5th, 2006 at 6:19 am

Sigh, everyone's a critic.

I don't know that this article will ever see a revision, but if it does, I shall keep your comments in mind.

Calin Culianu said, in December 13th, 2006 at 5:45 pm

Your sample code fails to compile cleanly on newer compilers. I guess that's because it was written back in 1996. At any rate thanks for taking the time to explain this. After reading your article I still don't really understand it -- and I am not sure if that's because I am too stupid your your article isn't clearly enough writte. *Shrugs*

Mark said, in December 13th, 2006 at 8:16 pm

Hi Calin,

Let me know what compiler you are using, I might take a try at updating the source.

The big problem was that in 1996 there weren't any compilers that came anywhere near conforming to today's standard, which wasn't ratified until 1998.

As for understanding it, I agree that it's hard - I wrote the article because I had such a hard time with it myself. I encourage you to try to work through some of the problems by hand, then see if you can duplicate the results with the debug version of the program and see if you get the same results.

Mark said, in December 26th, 2006 at 3:00 pm

Updated source code released, see the end of the article with the links!

Samuel said, in February 20th, 2007 at 2:21 pm

I'd like to say thank you.
This article and the source-code is definetly a big help in my diploma thesis where I need a suffix tree as a tool.

Mark said, in February 20th, 2007 at 3:27 pm

Thanks, Samuel, nice to hear.

Graham Reeds said, in February 21st, 2007 at 3:32 am

I like your code - currently implementing the BWT algorithm with just RLE as a preprocessor for XML transfer.

A couple of points:
* Make a link to this article from the BWT one - you mention suffix trees help speed up BWT compilation, but I had to go searching and found this site from Wikipedia.
* Lots of comments in the source - you tried Doxygen which would make the comments more searchable.

tony said, in February 23rd, 2007 at 4:55 pm

hey mark, how can i use your code to tell me the index of a substring in a text?

Mark said, in February 25th, 2007 at 12:22 pm

>hey mark, how can i use your code to tell me the index of a substring in a text?

Tony, that's kind of the whole point of the article, right?

Use the code in walk_tree as an indication of how to navigate the tree.

Once you walk the tree, searching for a match to your text, you will end up at either a leaf or an interior node.

If you are at leaf, you have found the only occurrence of the string, and can determine where it is by looking at the members of Suffix.

If you are at an interior node, you have found the root of a tree that will provide all the locations of the string in the text.

Good exercise to write this search routine!

Mark said, in February 27th, 2007 at 6:36 am

Hi Graham,

Believe it or not, when I wrote this article, Doxygen didn't handle C code very well - mostly because it didn't exist yet!

I don't spend too much time going back and fixing up old articles, mostly because of my belief in the inspiration words of Samuel Johnson:

"No man but a blockhead ever wrote, except for money."

Shivam said, in March 2nd, 2007 at 12:28 pm

How can I find the position(s) of the search string ?? What if there are wildcharacters in the pattern, can you recommend some references ?? Thanks

Mark said, in March 2nd, 2007 at 1:23 pm

Shivam, do you realize that string searching occupies at least one chapter in virtually every algorithms book?

A search on Google for "string search algorithms" gets you 3.5 million hits.

If you can't find some decent references on this, you aren't trying very hard.

Sorry to be harsh, but seriously, I can help you with specific problems related to the data compression on my site, but general questions that can be easily answered, well, you need to manage yourself.

cariaso said, in March 15th, 2007 at 11:02 pm

Mark, while I agree with your sentiments for Shivam, I can't resist pointing out:

"string searching occupies at least one chapter in every single algorithms book is dedicated to string searching"

If a book is dedicated to string searching, it seems a bit redundant to say that string searching occupies at least one chapter.

This article was tremendously valuable a decade ago. Since then there have been advances, especially coming from bioinformatics. Anyone interested in the topic should investigate:

An updated C implementation
http://www.icir/christian/libstree/

general notes
http://homepage.usask.ca/~ctl271/857/suffix_tree.shtml

big strings in small memory
http://csdl2puter/persagen/DLAbsToc.jsp?resourcePath=/dl/trans/tk/&toc=comp/trans/tk/2005/01/k1toc.xml&DOI=10.1109/TKDE.2005.3

a pairwise bioinformatics related tool
http://mummer.sourceforge/

a generalized bioinformatics tool
http://bibiserv.techfak.uni-bielefeld.de/mga/

Mark said, in March 17th, 2007 at 1:11 pm

Thanks for the excellent links and comments Michael! As for the proofreading, well, that's what comes of having no editor. i think I will violate the integrity of my blog comments by correcting it without leaving a trail.

eNG-sIONG said, in March 28th, 2007 at 1:40 am

Dear All,
I found this, may be useful, its a Standard Template Library for Extra Large Data Sets
implemented by Roman Dementiev that support a multiple type of container.
Theres no suffix tree yet. :(

http://stxxl.sourceforge/
Eng Siong

Diamante said, in April 11th, 2007 at 5:31 pm

Cool

Ha Luong said, in July 2nd, 2007 at 4:19 am

Hi Mark,
I have read your article and I couldn't understand the "active point". The active point is the first non-leaf ? (And I don't know the first non-leaf) . Could you please show me what the active point is in your figure 6 ?
Thanks so much ,
Ha Luong

Mark said, in July 2nd, 2007 at 6:55 am

Ha Luong,

I think my wording in that paragraph is not as good as it could be.

When I refer to the "first suffix that doesn't terminate in a leaf node", I am talking about the first suffix when considering the list of suffices:

BOOKK
OOKK
OKK
KK
K

Which is the list of suffixes you are now attempting to insert into the tree. Looking at Figure 5, you can see the suffix "K" terminates in the middle of the "KK" leaf node, which makes it the active point.

If you don't know what a non-leaf node is, you need to brush up on your data structures.

David Hou said, in July 12th, 2007 at 6:03 pm

Hi Mark, thank you for the excellent paper. It saves me from Esko Ukkonen's(that one is sooo hard, German folks are too smart .... ).

I still don't quite understand how the "end point" works, which is one crucial part of the whole thing. Could you kindly provide a sample to explain it more detail? thanks a lot.

Mark said, in July 15th, 2007 at 7:31 am

When performing the insertion of a new string, the two most important points are the active point and the end point.

The active point is discussed in the response above. When inserting a string into the tree, we look at the list of suffixes we are inserting. Some of the suffixes will be added to the tree by simple addition of a new character on an existing leaf node. The first suffix that can't be added by this simple extension is used to mark the active point.

I'll go back to the process of adding BOOKKE to Figure 5.

First, BOOKKE is added through simple extension of leaf node 1.
OOKKE is added through simple extension of leaf node 5.
OKKE is added through simple extension of leaf node 4.
KKE is added through extension of leaf node 2.

At this point, the tree looks like the first part of figure 6. You can see that when we attempt to add "KE" to the tree, things are not so simple. There is no leaf node that terminates in "K", so we can't just extend that leaf.

The suffix "K" is part of the tree, but it is an implicit node that is in the middle of the "KKE" branch terminating at node 2. (Part 1 of figure 6). The active point of the tree is now that implicit "K" node on the node 2 branch. (And that is where we will perform the split operation.)

Once you enter into the split operation at the active node, you can walk through the pseudocode to see what the elusive endpoint is:

if the implicit node's next char isn't test_char {
split the edge at the implicit node
create new leaf edge starting at the split in the edge
} else
done = true;

The end point is the first node where you don't have to perform a split as you add new suffixes.

Unfortunately I didn't include a good example showing this, so I need to add that to my to-do list.

David Hou said, in July 18th, 2007 at 11:18 am

Thank you Mark, i feel much clear now and I am trying to implement it in C#, oh... it's hard...

also, I found another tuition introduces Ukkonen's suffix tree and there's a demo is provide here: http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Tree/Suffix/#demoForm , the interesting thing is, when I run same string on your code and their code, I got different result... ... and idea about it ?

Mark said, in July 22nd, 2007 at 2:13 pm

Well, if you could show me a short demo string that comes up with different results for the two programs, I'd certainly be interested in seeing it!

arao said, in July 23rd, 2007 at 7:30 pm

the book by Prof. Dan Gusfield is a very good one on this.

and Esko Ukkonen is a German?? I thought he was from Finland...

Abhey Shah said, in July 30th, 2007 at 3:19 pm

On the Mac I found I needed to recast T[i] into chars before printing, or it would just give me numbers.

Mark said, in July 30th, 2007 at 5:15 pm

That seems kind of strange - T is typed as char. Casting at as a char should have no effect. Perhaps your compiler is using unsigned chars as default?

Abhey Shah said, in August 1st, 2007 at 9:45 am

I tried gcc3.3 on linux as well as gcc4.0 on the mac, same thing, that was just doing g -lstdc streed2006.cpp.
Anyway, if anybody else runs into the same thing sed 's/streed2007.cpp

Abhey Shah said, in August 1st, 2007 at 9:48 am

and of course the command lines get f***ed: got to love web 2.0. anyway I'm sure if anybody runs into the same thing they'll be able to piece together the edit commands.

Amit P said, in August 27th, 2007 at 5:07 am

i have been looking at the updated code and need to adapt it to take many different input strings and not just the one, i tried creating a loop for active and having each loop hold a different string however this has still not worked any ideas would be appreciated.

thanks

Amit P said, in August 28th, 2007 at 11:18 am

i added another line of input for T after addprefix loop, after the add input had the program recalculate N and added the for loop underneath, i will now try to write code that will input multiple strings from a loop. this did allow me to enter multiple strings into the same suffix tree.

Adam said, in September 4th, 2007 at 7:13 am

I see that IBM's Many-eyes data visualization community just put up a new visualization type called a Word tree (visual suffix tree).

http://services.alphaworks.ibm/manyeyes/page/Word_Tree.html

Mark said, in September 4th, 2007 at 7:49 am

That looks like a very nice visualization tool, it gives a nice understanding of how a suffix tree actually works.

Scott said, in September 17th, 2007 at 4:01 pm

>> On the Mac I found I needed to recast
>> T[i] into chars before printing, or it
>> would just give me numbers.
>
> That seems kind of strange - T is typed
> as char. Casting at as a char should
> have no effect. Perhaps your compiler is
> using unsigned chars as default?

I noticed the same issue with Visual C++ 2005. I believe the 'problem' was that overload resolution was finding the operator int() cast method in the Aux class, and was using that to cast to int and thus calling operator

Scott said, in September 17th, 2007 at 4:03 pm

Yuck, my post got mangled due to embedded less-than characters. Anyway, the overloaded int cast in the Aux class was preventing the Aux output method from being called.

till said, in October 12th, 2007 at 2:33 am

Enter string: aa
Start End Suf First Last String
0 1 -1 0 1 aa
Would you like to validate the tree?y
Suffix : aa
comparing: aa to aa
Suffix 0 count wrong!
Leaf count : 1 Error!
Branch count : 1 OK

Mark said, in October 12th, 2007 at 9:19 am

@till:

I suspect this is a corner case for n=2. You agree?

Rock Linker said, in November 7th, 2007 at 2:19 am

hi mark

appreciate for your sharing! Thank you so much!

btw: in your article, there is an conception "end point", in your former response you also explained that, however, I still have some questions about that. According to your explaination, "end point" is the first node that need not to be splited, but you know, end point is shorter than the active point, and active point must be splited, how can an "end point" node exist in the suffix tree? I am a little confused. Thank you! wait for your kindly response. Thanks a lot!

Mark said, in November 7th, 2007 at 12:21 pm

If we order the suffixes of a string in decreasing length:

Rock
ock
ck
k

The active point will be the first of these suffixes which does not terminate on a leaf node.

And like I said in the article, every suffix longer than the suffix at the active point terminates in a leaf. Every suffix short than the suffix at the active point does not.

As you are updating the suffix tree, you know you have reached the end point when an element in the suffix tree has the same descendant as the string you need to add at that point.

I don't know that there is a relationship between the end point and the active point. You seem to think there is some relationship between the end point and the active point, and I don't think that is true.

I suggest that in order to understand this, you just run through a few examples of moderate length to watch the active point, the end point, and the tree change in response to the addition of new suffixes.

Bryan said, in November 15th, 2007 at 1:53 am

I still don´t understand the linear time thing.
Every time we add a new character we need to go through all the suffix pointers. That means that the time spent in every step depemds on how many suffix pointers are. And the number of suffix pointers is variable.
If I am wrong, please explain me, because I don´t undertand.

Mark said, in November 15th, 2007 at 7:07 am

@Bryan:

Hi Bryan,

The place where you are off base is here:

>Every time we add a new character we need to
>go through all the suffix pointers.

If you look at either the pseudocode or the actual code, you'll see that we don't go through all the pointers, and that is what makes the algorithm efficient.

When it comes time to insert a new character, we start work at the active point:

PLAIN TEXT C++:
  1. Update ( new_suffix )
  2. {
  3.   current_suffix = active_point
  4.   test_char = last_char in new_suffix
  5.   done = false;
  6.   while ( !done ) {
  7.     if current_suffix ends at an explicit node {

Because we keep track of the active point, we know in advance where the next search is going to start, so we most definitely do not search through all the suffix pointers in order to insert a new suffix.

Try working through some insertions by hand and you'll see how it works more clearly.

Bryan said, in November 21st, 2007 at 2:03 am

Hi Mark:

Thank you for your soon reply. I´m going to try the insertions by hand. My doubt was more focused on how many times the while will be executed in the worst case. I´m going to check the article again and I hope I´ll get a better understanding of the algorithm.

Thank you for taking the time to read and reply.

Bryan said, in November 26th, 2007 at 6:47 pm

Hi Mark:

I´ve seen the light. At the end, the while has been executed as many times as branches are in the tree. And since the amount of branches is equal to the amount of leafs, the time remains linear.

Thank you for your time.

Bytes

Tim Rowe said, in November 29th, 2007 at 11:03 am

Many thanks for the clearest explanation of the algorithm that I've managed to find so far! I'm still struggling a little to understand it, but I think that's because it's genuinely tricky (or I'm genuinely thick) rather than any problems with the explanation. Off to try some examples on paper.

Tim Rowe said, in November 30th, 2007 at 8:43 am

What is the licensing situation on that code? Are we free to use it with acknowledgement in the code? Acknowledgement visible to the user? Apply to you for a licence?

Mark said, in December 1st, 2007 at 10:33 am

@Tim:

See the link at the top of the page: Liberal Code Use Policy.

But remember, this is demonstration code - you may be able to find something substantially more optimized elsewhere.

hlbnet said, in December 14th, 2007 at 11:43 am

I do not see how a suffix tree can be build in linear time (so you understand I'm not an expert).
I KNOW it is true (read everywhere), but I definitively don't understand how it is possible.
If I follow your explanations, to construct our suffix tree, we have to browse all the characters of the text (here is the O(n) I think) and for each, we have to append the new character to all suffixes that are already in our tree. Here, I see a loop on the already registered suffixes nested in the main loop on the characters. And the inner loop becomes bigger each time a new suffix is added.
Is there something magic somewhere that makes the whole algorithm finally linear ?

Mark said, in December 14th, 2007 at 11:54 am

@hlbnet:

The reason the algorithm runs in linear time is that appending a new suffix to the tree can be done in constant time. The reason the suffix can be appended in constant time is because we keep track of the active point.

If you look at the final version of the simplifed algorithm, you'll see that there is an outer loop that iterates over all the characters in the input sequence. But there's no inner loop. So the number of operations needed to create the whole tree is N*something, where something has an upper bound that is not dependent on N.

hlbnet said, in December 17th, 2007 at 10:11 am

I'm not fully convinced just reading the algo, since I see a

PLAIN TEXT C:
  1. while ( !done )

in the

PLAIN TEXT C:
  1. Udpdate ( newSuffix )

function (here is the inner loop).
I see that there are several stop conditions in the loop, making it stop rather "quickly". But it is still very hard for me to figure out the average number of loops that will be performed in a real example.
I definitively need to think of it more in depth.
Thank you for your article and answers, it is very usefull for beginners like me !

Iena said, in February 14th, 2008 at 3:07 am

Hi Mark..
Thanks on your article..a very big help for my thesis..;)

Fan said, in March 3rd, 2008 at 4:15 pm

Hi Mark,

Thank you for the good article.

I have one question about how to update suffix tree, would you please give me some suggestions? Thank you very much.

I have modified your source code in order to insert a new string to the suffix tree, update the suffix tree if new string doesn't exist in the suffix tree. Unfortunately, I was stuck on updating the suffix tree.

Here is an example, first inserts "hello" to the suffix tree which looks like:
Start End Suf First Last String
0 2 -1 1 4 ello
0 1 -1 0 4 hello
0 4 0 2 2 l
0 6 -1 4 4 o
4 3 -1 3 4 lo
4 5 -1 4 4 o

then inserts "bok" to the suffix tree, first character 'b' is added without any problem,
Start End Suf First Last String
0 2 -1 1 4 ello
0 1 -1 0 4 hello
0 4 0 2 2 l
0 6 -1 4 4 o
4 3 -1 3 4 lo
4 5 -1 4 4 o
0 7 -1 5 7 bok

then 'o' is being added to the suffix tree, it was found in the suffix tree, which indicates by start node 0, end node 6. continuing on next character 'k', it first should append 'k' to leaf node 'o' and update its first and last character in the string from (4, 4) to (6, 7), then creates a new edge to represent 'k' and insert into the suffix tree. How should I modify the code on those steps?

The correct suffix tree should look like the following structure:

Start End Suf First Last String
0 2 -1 1 4 ello
0 1 -1 0 4 hello
0 4 0 2 2 l
0 6 -1 4(6) 4(7) ok
4 3 -1 3 4 lo
4 5 -1 4 4 o
0 7 -1 5 7 bok
0 8 -1 7 7 k

Mark Nelson said, in March 4th, 2008 at 11:01 pm

@Fan:

Well, I'm not sure what you are doing makes any sense. If you already have "hello" in the tree, you can't have "bok" by itself, it has to be a suffix of some existing string in the tree. So when adding the "b", you should have "hellob" in the tree.

Your modified algorithm doesn't.

So whatever you are trying to make is not really a suffix tree.
=Mark

PT said, in April 21st, 2008 at 6:54 pm

Does any know of a good Trie / suffix tree implementation in c#?

Mark Nelson said, in April 21st, 2008 at 8:39 pm

@PT:

I'd take a look at codeproject, and perhaps search krugle.

sarba said, in April 23rd, 2008 at 1:29 am

@sarba
Hi Mark,
I want to modify your code to find all exact repeat positions of an input string .For example String S=ATAGGATAGC .I want to find repeat (here ATA) and there positions (here 0,5).Can you give me any suggestion about how to modify the code?

Mark Nelson said, in April 23rd, 2008 at 7:46 am

@sabra: I'm not sure I understand the question.

sarba said, in April 24th, 2008 at 12:29 pm

hi mark,
Thanks for your attention.ok forget the above question for time being . More simply can you explain me how can I find longest common substring of input string. Suppose I have two string
a. ATATGCATCAG
b. GCATGCACCGA
I want to find longest common substring of the two sequences. What I did is as follow,
I concatenate two string like this S=ATATGCATCAG#GCATGCACCGA then made suffix tree .Theoretically the edge from root node to the depth est internal node contains the longest common substring.So how can I find the depthest intenal node and its "edge level" from root.

prodvit said, in May 21st, 2008 at 4:24 am

Hi mark. I read your article and I found it very useful. I'm interesting in suffix trees for building a web search results clustering algorithm, like STC (Zamir et Etzioni, 1998).

I'm interested in understanding the difference between suffix trees and suffix arrays, in particular I would understand advantage in using one rather than other in clustering problems.

Can you help me?

Thanks
Massimiliano

Mark Nelson said, in May 21st, 2008 at 5:57 am

@prodvit:

I wish I could give you a good answer here, but I don't know a lot about suffix arrays - I need to get up to speed there myself. All I know for sure is that suffix trees are advertised as having good construction costs, and once constructed, should be just as useful as suffix trees.

void said, in May 28th, 2008 at 3:24 am

Just wanted to let you know that I thought your article was good. Clear and more understandable than alot of other articles on suffix trees I've looked at.

Good work, thanks for sharing.

Mark Nelson said, in May 28th, 2008 at 7:23 am

@void:

Thanks for the kind words. For some reason this is a tough algorithm to explain, to understand, and to illustrate. Some day in the far off future I'm going to take another crack at it and see if I can do better!

giorgos said, in June 5th, 2008 at 4:34 am

Hi mark,
thanks for your article!
Is it possible to decribe what happens with the string MISSISSIPPI ?
Actually, i dont understand the step adding the MISSIS suffix.
i read the following link and its really confusing
http://www.allisons/ll/AlgDS/Tree/Suffix/

Mark Nelson said, in June 5th, 2008 at 5:15 am

@girgos,

If you're having trouble with the description on the web site shown in your comment, why not ask the owner of that site for clarification?

giorgos said, in June 5th, 2008 at 11:06 am

Thanks for your quick response, Mark!

I read your example with Bookeeper, but when i tried to create the tree for MISSISSIPPI, i had some problems.
It would be great and you would help me a lot if you gave us a succinct example with the string MISSISSIPPI too.

Thanks,
Giorgos

xyzzy said, in June 16th, 2008 at 6:48 am

Hi, thanks for the nice article. It would be better if you add a few examples though, like how strees can be used for finding the longest common substring etc.

xyzzy said, in June 16th, 2008 at 7:52 am

Ok. Here's one solution I found. When you find a character that's already an implicit node, mark a $ under it so that the next character encountered will be added to this $ also.

Tamer said, in July 1st, 2008 at 3:38 pm

Hi,

Nice work. I am working on a research project that requires building a large suffix tree (around 20k string, each with 4 to 8 letters). I worked on your code, and i guess the main problem is in the hash array. I mean if i can enlarge the hash array, i can store the large number of edges in the tree.
Could you please provide me with some way to change the hashing function so that to be able to generate a number between 0 and 20k or 30k.

Thanks,
Tamer

Leave A Reply

You can insert source code in your comment without fear of too much mangling by tagging it to use the iG:Syntax Hiliter plugin. A typical usage of this plugin will look like this:

[c]
int main()
{
printf( "Hello, world!/n" );
return 1;
}
[/c]

Note that tags are enclosed in square brackets, not angle brackets. Tags currently supported by this plugin are: as (ActionScript), asp, c, cpp, csharp, css, delphi, html, java, js, mysql, perl, python, ruby, smarty, sql, vb, vbnet, xml, code (Generic).

If you post your comment and you aren't happy with the way it looks, I will do everything I can to edit it to your satisfaction.


Looking to get your programming degree? This online college and learning center has the bachelor degree in the field you're looking for!

Links From Google


<script type=text/javascript> </script> <script src="http://pagead2.googlesyndication/pagead/show_ads.js" type=text/javascript> </script> <script> window.google_render_ad(); </script>

Amazon Books


<script type=text/javascript> </script> <script src="http://www.assoc-amazon/s/ads.js" type=text/javascript></script>

Bookmarks/Feeds

Use the first button below to bookmark this article on sites like del.icio.us, Digg, Reddit, Slashdot, etc. The second button adds a feed for the site to your reader. Both buttons will open a selection screen in a new window.

Categories

Standards Scams Humor VoIP Work Culture Hackery Writing Snarkiness Video Graphics People Audio Web Articles Business Computer Science Programming Complaining Magazine Articles Data Compression

Recent Entries

  • Innumeracy Part N
  • Slate Rips Me Off
  • Another One Bites the Dust
  • English as a Foreign Language - A Cautionary Tale
  • How Evil Is Apple?
  • Cashing in On Electronic Books
  • Jerome Kerviel, My Hero
  • I Trust American Express With My Money?
  • Algorithms Crossword
  • Help Needed

Blogroll

  • Joey Nelson - Joey Nelson
  • Obviosaurus - It's obvious

My Books

  • The Data Compression Book
  • Serial Communications: A C++ Developer's Guide, 1st. ed.
  • Serial Communications: A C++ Developer's Guide, 2nd ed.
  • C++ Programmer's Guide to the Standard Template Library
  • Developing Cisco IP Phone Services: A Cisco AVVID Solution

Archives

Recent Comments

  • David Jones in Innumeracy Part N
  • Mark Nelson in No Exceptions - With One Exception
  • Alan Morris in No Exceptions - With One Exception
  • Mark Nelson in C++ Hash Table Memoization: Simplif…
  • dan in C++ Hash Table Memoization: Simplif…
  • Mark Nelson in The Million Random Digit Challenge …
  • Anash in The Million Random Digit Challenge …
  • Myself in The Data Compression Book
  • manjunath in Serial Communications: A C++ Develo…
  • manjunath in Serial Communications: A C++ Develo…
©1996  Mark Nelson
Powered by WordPress | Talian designed by VA4Business, Virtual Assistance for Business who's blog can be found at Steve Arun's Virtual Marketing Blog   网址: http://marknelson.us/1996/08/01/suffix-trees/ <script type=text/javascript charset=utf-8> /* * Some javascript created by Joey to mung all class newpage links and ensure * that they have a target="_blank" destination. - added by MRN */ var links = document.getElementsByTagName('a'); for (var l=0, pos=0; l < links.length; l++) { if(links[l].className.indexOf("newpage") != -1){ links[l].target = "_blank"; } } </script> <script src="http://www.google-analytics/urchin.js" type=text/javascript> /* * My google analytics tracking code - added by MRN */ </script> <script type=text/javascript> _uacct = "UA-747044-1"; urchinTracker(); </script>

更多推荐

Fast String Searching With Suffix Trees