The Suffix Tree and Suffix Array

Matt George

Fractional CTO · Founder of Injuria.ai

•19 min read•

The Suffix Tree and Suffix Array

String matching is a foundational problem in computer science, concerned with finding occurrences of a specific pattern within a larger body of text. When the text is static and queried frequently, scanning the entire text for every query becomes computationally prohibitive. To solve this, computer scientists developed full-text indices, which preprocess the text into a structured format that allows for rapid pattern matching. The two most prominent data structures in this domain are the suffix tree and the suffix array.

The suffix tree is a highly compressed trie that stores all suffixes of a given string.[25] It allows for pattern matching in time proportional only to the length of the pattern, entirely independent of the length of the text. Despite its theoretical elegance and optimal search time, the suffix tree suffers from a high memory overhead due to the large number of internal nodes and pointers required to represent the tree structure. This memory consumption makes it impractical for indexing massive datasets like complete human genomes.

To address the memory limitations of the suffix tree, the suffix array was introduced as a space-efficient alternative.[26] A suffix array is simply an array of integers representing the starting positions of all suffixes of the text, sorted in lexicographical order.[27] While it slightly increases the theoretical search time by introducing a logarithmic factor based on the text length, it reduces the memory footprint significantly. When augmented with auxiliary structures like the Longest Common Prefix array, the suffix array can match the optimal search time of the suffix tree and simulate all of its advanced operations, making it the dominant full-text index in modern software.[27]

The Substring Search Problem

The exact substring search problem is formulated as follows: given a large text string of length $n$ and a shorter pattern string of length $m$, the objective is to locate every index in the text where the pattern appears as a contiguous sequence of characters. The exact mathematical formulation of the problem highlights the distinction between the text length $n$ and the pattern length $m$. In typical scenarios, $n$ is orders of magnitude larger than $m$. A genomic database might contain billions of nucleotide bases, while a researcher might query a short sequence of just 50 bases.

Historically, algorithms approached this problem by preprocessing the pattern rather than the text. The Knuth-Morris-Pratt algorithm Knuth et al., 1977[1] analyzes the pattern to build a partial match table, which dictates how far the pattern can be shifted along the text after a mismatch, avoiding redundant character comparisons. The Boyer-Moore algorithm Boyer and Moore, 1977[2] uses a similar philosophy, scanning the pattern from right to left and using a bad character rule to skip large sections of the text. Both algorithms achieve a search time of $O(n + m)$.

Other approaches focused on different aspects of the problem. The Aho-Corasick algorithm Aho and Corasick, 1975[3] constructs a finite state machine from a dictionary of patterns, allowing multiple patterns to be searched simultaneously in $O(n + M + z)$ time, where $M$ is the sum of the lengths of all patterns in the dictionary and $z$ is the number of matches. The Rabin-Karp algorithm Karp and Rabin, 1987[4] utilizes a rolling hash function to filter out impossible matches rapidly, which is particularly useful for detecting plagiarism or matching multiple patterns.

While $O(n + m)$ is theoretically optimal for a single query on an unstructured text, it is highly inefficient for environments where the text is static and queried repeatedly by thousands of different patterns. An unstructured search algorithm must process the entire sequence to find a match. If a researcher needs to query one million different 50-base sequences against a three billion base genome, the unstructured approach requires quadrillions of operations. To achieve sublinear search times, specifically search times that depend only on the length of the pattern $m$ and not on the length of the text $n$, the text itself must be preprocessed into a searchable index.

The fundamental insight behind full-text indices is that any substring of a text is necessarily a prefix of some suffix of that text. For example, in the text "banana", the substring "nan" is a prefix of the suffix "nana". Therefore, if a data structure can efficiently store and retrieve all possible suffixes of a text, it inherently acts as a directory of all possible substrings. The suffix tree and the suffix array are the two primary data structures built upon this mathematical property. By organizing the suffixes lexicographically or hierarchically, these indices allow search algorithms to bypass the $n$ characters of the text and locate patterns in $O(m)$ or $O(m \log n)$ time.

Suffix Trees: Structure and Mechanism

A suffix tree is a specialized, compressed trie that represents all suffixes of a given string.[25] Let the text be a string of length $n$ drawn from a finite alphabet. To ensure that no suffix is a proper prefix of another suffix, a unique terminal symbol, typically denoted as $, is appended to the end of the text. This terminal symbol does not appear anywhere else in the alphabet. This guarantees that every suffix ends at a distinct leaf node.

The conceptual foundation of a suffix tree is a standard trie, a tree structure where each edge represents a single character, and every path from the root to a leaf spells out a complete suffix. However, a standard trie for all suffixes of a text of length $n$ requires $O(n^2)$ nodes in the worst case. For a text of one million characters, a standard trie could require a trillion nodes, which is computationally impossible to store.

The suffix tree resolves this by applying path compression. Any path of nodes where each node has exactly one child is collapsed into a single edge. Let us consider a concrete example using the string "banana$". The suffixes are "banana$", "anana$", "nana$", "ana$", "na$", "a$", and "$". In a standard trie, representing these seven suffixes would require creating individual nodes for every character of every suffix, resulting in significant redundancy. The suffix tree compresses this by merging non-branching paths. The path for "na$" and "nana$" will share a common edge labeled "na", which then branches into two separate edges labeled "$" and "na$".

Instead of being labeled with explicit strings, the compressed edges are labeled with substrings of the text. Because these substrings are contiguous segments of the original text, they do not need to be stored explicitly in the tree. Each edge label is represented by two 32-bit or 64-bit integers: the starting index and the ending index of the substring in the original text array.

This compression guarantees that every internal node in the tree has at least two children. For a text of length $n$, the resulting suffix tree has exactly $n$ leaf nodes and a maximum of $n - 1$ internal nodes. The space complexity of the tree is therefore strictly $O(n)$.

Searching for a pattern of length $m$ in a suffix tree is highly efficient. The algorithm begins at the root and traverses down the tree, matching the characters of the pattern against the characters on the edge labels. If the algorithm successfully matches all $m$ characters, the search is successful. The subtree rooted below the point of the final match contains leaf nodes that correspond to every starting position of the pattern in the text. The time required to find the match is exactly $O(m)$, which is optimal. Finding all $k$ occurrences takes an additional $O(k)$ time to traverse the subtree and collect the leaf indices.

Despite the $O(n)$ theoretical space complexity, the constant factors hidden in the Big-O notation are severe. Each internal node requires memory for child pointers, sibling pointers, and suffix links. In a typical implementation, a suffix tree consumes 10 to 20 bytes of memory per character of the text. For a three gigabyte human genome, a suffix tree requires up to 60 gigabytes of random access memory. This massive overhead limits the utility of suffix trees to smaller datasets or specialized high-memory servers.

Suffix Arrays: Structure and Mechanism

The suffix array was designed to provide the same search capabilities as the suffix tree but with a drastically reduced memory footprint. A suffix array for a text of length $n$ is an array of $n$ integers. Each integer represents the starting index of a suffix in the text. The defining characteristic of the suffix array is that these integers are ordered such that the suffixes they point to are sorted in exact lexicographical (alphabetical) order.[28]

Because the suffixes are lexicographically sorted, all suffixes that share a common prefix are grouped together in a contiguous block within the array. Searching for a pattern in a suffix array is equivalent to finding this contiguous block. Since the array is sorted, the search can be performed using a standard binary search algorithm.

To find a pattern of length $m$, the binary search compares the pattern against the suffix at the middle index of the current search interval. The string comparison takes up to $O(m)$ time. Based on the lexicographical comparison, the search interval is halved. Since there are $\log n$ halving steps, the total time complexity for a naive binary search on a suffix array is $O(m \log n)$.

def find_lower_bound(text, pattern, suffix_array):
    left = 0
    right = len(suffix_array) - 1
    m = len(pattern)
    result = -1
    
    while left <= right:
        mid = (left + right) // 2
        suffix_start = suffix_array[mid]
        
        match_len = 0
        while match_len < m and suffix_start + match_len < len(text):
            if text[suffix_start + match_len] != pattern[match_len]:
                break
            match_len += 1
            
        if match_len == m:
            result = mid
            right = mid - 1 
        elif text[suffix_start + match_len] < pattern[match_len]:
            left = mid + 1
        else:
            right = mid - 1
            
    return result

While $O(m \log n)$ is slightly slower than the $O(m)$ time of a suffix tree, the suffix array requires only 4 bytes per character, assuming 32-bit integers are sufficient to index the text. This reduces the memory requirement for a human genome from 60 gigabytes to exactly 12 gigabytes.

To eliminate the $O(\log n)$ penalty, the suffix array is augmented with a Longest Common Prefix (LCP) array. The LCP array is an array of integers where the value at index $i$ stores the length of the longest common prefix between the suffix at suffix array index $i$ and the suffix at index $i - 1$. By using the LCP array during the binary search, the algorithm can avoid re-comparing characters that have already been matched in previous iterations. Specifically, if the search algorithm knows the exact length of the prefix shared between the pattern and the boundaries of the current search interval, it can skip those characters entirely.

This enhancement reduces the search time to $O(m + \log n)$. The combination of a suffix array and an LCP array can simulate any top-down traversal of a suffix tree. Every internal node in a suffix tree corresponds to an interval in the suffix array, and the depth of that node corresponds to a value in the LCP array. This equivalence allows the enhanced suffix array to replace the tree entirely in advanced string processing tasks.

Algorithmic Construction

The theoretical foundations of full-text indexing were established over several decades of algorithmic research. The suffix tree was the first of the two structures to be formalized. It was introduced by Peter Weiner in 1973 Weiner, 1973[5]. Weiner called the structure a "position tree" and provided the first linear time construction algorithm. His algorithm processed the text from right to left, inserting suffixes into the tree. Donald Knuth reportedly characterized Weiner's discovery as the "algorithm of the year" due to its unexpected linear time bound.

In 1976, Edward McCreight published a significant refinement to Weiner's work McCreight, 1976[6]. McCreight's algorithm processed the text from left to right and drastically reduced the memory overhead during construction. He achieved this by introducing "suffix links," which are pointers from an internal node representing a string $aX$ to another internal node representing the string $X$. Suffix links allow the construction algorithm to jump across the tree, avoiding redundant traversals and ensuring the $O(n)$ time complexity.

The most widely taught method for suffix tree construction was published by Esko Ukkonen in 1995 Ukkonen, 1995[7]. Ukkonen's algorithm is an online algorithm, meaning it reads the text character by character from left to right and maintains a valid suffix tree for the prefix of the text read so far. It achieves linear time by maintaining an "active point" (a reference to the current location in the tree) and a "remainder" counter (the number of suffixes currently being inserted). When a new character is read, the algorithm uses suffix links to rapidly traverse the tree and insert the new character at all necessary locations. Dan Gusfield's 1997 textbook, "Algorithms on Strings, Trees and Sequences," heavily popularized Ukkonen's algorithm and cemented the suffix tree as a central topic in computational biology Gusfield, 1997[8].

A limitation of these early algorithms was their dependence on the size of the alphabet. For integer alphabets, Martin Farach introduced an algorithm in 1997 that achieved linear time construction independent of the alphabet size Farach, 1997[9].[29] Farach's approach recursively built a suffix tree for the odd-indexed suffixes, then used this structure to build the tree for the even-indexed suffixes, and finally merged the two trees. This divide-and-conquer strategy became the blueprint for later suffix array construction algorithms.

Despite these algorithmic triumphs, the memory consumption of suffix trees remained a practical barrier.[26] In 1990, Udi Manber and Gene Myers introduced the suffix array specifically to solve this memory problem, later publishing their complete findings in 1993 Manber and Myers, 1993[10].[30][31] They provided an elegant $O(n \log n)$ time algorithm to construct the array by sorting the suffixes based on prefixes that double in length at each iteration.

For over a decade, it was unknown whether a suffix array could be constructed directly in linear time without first building a suffix tree. This open problem was resolved in 2003 when three independent groups of researchers published $O(n)$ construction algorithms simultaneously. Juha Karkkainen and Peter Sanders introduced the skew algorithm (also known as DC3), which divides the suffixes into subsets based on their indices modulo 3, sorts one subset recursively, and merges the results Karkkainen and Sanders, 2003[11]. Pang Ko and Srinivas Aluru developed an algorithm based on classifying suffixes as smaller or larger than their adjacent suffixes Ko and Aluru, 2003[12].

The linear time construction of the LCP array was solved by Toru Kasai, Gunho Lee, Hiroki Arimura, Setsuo Arikawa, and Kunsoo Park in 2001 Kasai et al., 2001[13]. Their algorithm uses the inverse suffix array to compute the longest common prefixes in $O(n)$ time. It relies on the mathematical observation that if the LCP of a suffix is $h$, the LCP of the next suffix in the text must be at least $h - 1$. This prevents the algorithm from rescanning characters, bounding the total number of comparisons to $2n$. This made the suffix array a complete theoretical replacement for the suffix tree, a concept formalized by Mohamed Ibrahim Abouelhoda, Stefan Kurtz, and Enno Ohlebusch in 2004 as the "enhanced suffix array" Abouelhoda et al., 2004[14].

In 2009, Ge Nong, Sen Zhang, and Wai Hong Chan published the SA-IS algorithm Nong et al., 2009[15]. SA-IS improved upon the Ko and Aluru method by classifying characters as S-type (lexicographically smaller than the suffix to their right) or L-type (lexicographically larger). The algorithm identifies Leftmost S-type (LMS) characters, which are S-type characters immediately following an L-type character. The substrings between LMS characters are sorted, and this partial order is used to induce the order of the L-type suffixes, which in turn induces the order of the remaining S-type suffixes. SA-IS requires almost no auxiliary workspace and is so fast in practice that it became the standard algorithm for suffix array construction Puglisi et al., 2007[16].

Important Variants

The basic suffix tree and suffix array index a single string. In many applications, it is necessary to index a collection of strings, such as a database of thousands of documents or a set of multiple chromosomes. The Generalized Suffix Tree and Generalized Suffix Array handle this by concatenating all strings in the collection, separating them with unique terminal symbols (for example, $1, $2, $3). These terminal symbols must be lexicographically distinct and not present in the original alphabet to ensure that a suffix from one string cannot be artificially extended by characters from another. The algorithms operate on the concatenated string, allowing for cross-document substring queries.

As datasets grew into the terabyte range, even the 4 bytes per character required by a suffix array became a bottleneck. This led to the development of compressed full-text indices. In 2000, Roberto Grossi and Jeffrey Vitter introduced the Compressed Suffix Array, which uses hierarchical sampling to represent the suffix array in space proportional to the entropy of the text, rather than the length of the text Grossi and Vitter, 2005[17].

In the same year, Paolo Ferragina and Giovanni Manzini introduced the FM-index Ferragina and Manzini, 2000[18]. The FM-index is an opportunistic data structure based on the Burrows-Wheeler Transform, a block-sorting algorithm originally designed for data compression by Michael Burrows and David Wheeler in 1994 Burrows and Wheeler, 1994[19]. The Burrows-Wheeler Transform is constructed by forming a matrix of all cyclic permutations of the text, sorting the rows lexicographically, and extracting the last column. Because the cyclic shifts are sorted lexicographically, the order of the rows corresponds exactly to the suffix array.

The FM-index compresses this last column and adds auxiliary data to support a mechanism called backward search. Backward search allows a pattern to be counted in time proportional to the pattern length, but locating requires additional time per occurrence depending on the suffix array sampling rate, while the index itself occupies less space than the original uncompressed text. The core mechanism enabling the FM-index is the LF-mapping (Last-to-First mapping), a mathematical property of the Burrows-Wheeler matrix. The LF-mapping guarantees that the $i$-th occurrence of a character in the last column of the sorted matrix corresponds to the exact same text position as the $i$-th occurrence of that character in the first column. This allows the algorithm to navigate backward through the text, character by character, without explicitly storing the matrix or the original text.

Real-World Applications

The most profound impact of suffix trees and suffix arrays has been in the field of bioinformatics. The sequencing of the human genome and the subsequent explosion of next-generation sequencing technologies generated massive volumes of DNA data. Identifying the origin of short DNA reads by aligning them to a reference genome is a daily task in computational biology.

MUMmer, developed by Arthur Delcher, Simon Kasif, and Steven Salzberg in 1999, was one of the first systems to align whole genomes Delcher et al., 1999[20]. MUMmer relies heavily on suffix trees to find Maximal Unique Matches between two DNA sequences, allowing researchers to identify mutations, structural variations, and evolutionary divergence.

As sequencing reads became shorter and more numerous, the memory overhead of suffix trees became a liability. The bioinformatics community transitioned to tools based on the Burrows-Wheeler Transform and the FM-index. Bowtie, published by Ben Langmead and colleagues in 2009, uses an FM-index to align millions of short reads per hour with a memory footprint of just 1.3 gigabytes Langmead et al., 2009[21]. In the same year, Heng Li and Richard Durbin released the Burrows-Wheeler Aligner, which also utilizes the FM-index and backward search to achieve fast and accurate alignments allowing for mismatches and gaps Li and Durbin, 2009[22].

Beyond biology, suffix arrays and their compressed variants are used extensively in data compression. The Burrows-Wheeler Transform is the core algorithm inside the widely used bzip2 compression utility bzip2, 1996[23]. By sorting the suffixes, the transform groups similar characters together, creating long runs of identical characters that are highly compressible using move-to-front coding and Huffman coding Huffman, 1952[24].

In information retrieval, suffix arrays are used for plagiarism detection, code clone detection, and full-text search in languages where word boundaries are not clearly defined, such as Chinese or Japanese. Because the suffix array groups identical substrings together, the algorithm can rapidly identify large blocks of copied text even if the surrounding words have been altered. Unlike inverted indices, which index text at the word level, suffix arrays index text at the character level, allowing for arbitrary substring queries without tokenization.

Significance and Tradeoffs

The choice between a suffix tree, a suffix array, and an FM-index depends entirely on the available memory and the specific requirements of the query.

The suffix tree offers the most intuitive traversal and the fastest theoretical query time. It is ideal for complex string analytics, such as finding the longest repeated substring, finding the longest common substring of multiple documents, or identifying palindromes. However, its massive memory consumption restricts its use to smaller texts or systems with enormous memory capacity.

The suffix array strikes a balance between memory and speed. By requiring only an array of integers, it fits comfortably in the memory of standard workstations even for gigabyte-sized texts. When paired with the Longest Common Prefix array, it matches the analytical power of the suffix tree. Modern computer architectures favor the suffix array due to cache locality. Traversing a suffix tree involves following pointers to arbitrary memory locations, which causes frequent cache misses. Binary searching a suffix array involves reading contiguous blocks of memory, which is highly optimized by modern CPU caches.

The FM-index and Compressed Suffix Arrays represent the extreme end of the memory optimization spectrum. They allow massive datasets to be indexed and searched on consumer-grade hardware. The tradeoff is a slower query time, as locating the exact position of a match requires repeatedly applying the inverse Burrows-Wheeler Transform to reconstruct the original text position.

Together, these data structures form a complete hierarchy of solutions for the substring search problem. From Weiner's initial discovery of the position tree to the highly optimized induced sorting algorithms of the modern era, the evolution of the suffix tree and suffix array demonstrates a continuous refinement of time and space complexity, enabling the analysis of the largest datasets in science and industry.

Sources (31)
  1. Knuth et al., 1977
  2. Boyer and Moore, 1977
  3. Aho and Corasick, 1975
  4. Karp and Rabin, 1987
  5. Weiner, 1973
  6. McCreight, 1976
  7. Ukkonen, 1995
  8. Gusfield, 1997
  9. Farach, 1997
  10. Manber and Myers, 1993
  11. Karkkainen and Sanders, 2003
  12. Ko and Aluru, 2003
  13. Kasai et al., 2001
  14. Abouelhoda et al., 2004
  15. Nong et al., 2009
  16. Puglisi et al., 2007
  17. Grossi and Vitter, 2005
  18. Ferragina and Manzini, 2000
  19. Wikipedia: Burrows and Wheeler, 1994
  20. Delcher et al., 1999
  21. Langmead et al., 2009
  22. Li and Durbin, 2009
  23. bzip2, 2010
  24. Huffman, 1952
  25. Alberto Apostolico, Maxime Crochemore, Kunsoo Park, Combinatorial Pattern Matching (Springer, 2005)
  26. Donald Adjeroh, Timothy Bell, Amar Mukherjee, The Burrows-Wheeler Transform: (Springer Science & Business Media, 2008)
  27. Frédéric Benhamou, Narendra Jussien, Barry A. O'Sullivan, Trends in Constraint Programming (John Wiley & Sons, 2013)
  28. Michael Doumpos, Constantin Zopounidis, Panos M. Pardalos, Financial Decision Making Using Computational Intelligence (Springer Science & Business Media, 2012)
  29. Felipe A. Louza, Simon Gog, Guilherme P. Telles, Construction of Fundamental Data Structures for Strings (Springer Nature, 2020)
  30. Steven S. Skiena, The Algorithm Design Manual (Springer Nature, 2020)
  31. Johannes Fischer, Peter Sanders, Combinatorial Pattern Matching (Springer, 2013)

Recommended reading