Notes
All notes

Suffix Trees and Arrays (DSA #18)

“Does this 10 MB DNA string contain this pattern?” “What is the longest repeated substring?” “Compare these two documents for the longest common section.” A hash set cannot answer these because they are about all substrings, and a string of length \(n\) has \(\Theta(n^2)\) substrings. Suffix structures store the structure of every suffix in only \(O(n)\) space, turning substring and repeat queries into fast lookups.

This chapter covers the two practical tools: the suffix array, which is a sorted list of suffixes, and the suffix tree, its compressed-tree cousin.

Suffixes, and why storing them naively fails

The suffixes of banana are banana, anana, nana, ana, na, a. There are \(n\) of them, and together they contain all substrings. Storing each suffix as a string is \(O(n^2)\) space — 100 GB for a 10 MB string. Suffix structures store the ordering and shared structure instead, in \(O(n)\).

Suffix array: suffixes in sorted order

A suffix array SA is the list of starting indices of all suffixes, sorted lexicographically. For banana:

suffix start
a 5
ana 3
anana 1
banana 0
na 4
nana 2

So SA = [5, 3, 1, 0, 4, 2]. That is \(O(n)\) integers — the whole structure, regardless of how many substrings there are.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.75cm, minimum height=0.62cm, font=\small\bfseries}]
  \node[font=\small, anchor=west] at (-2.3,0) {SA:};
  \foreach \v [count=\i from 0] in {5,3,1,0,4,2} { \node[c, fill=blue!10] at (\i*0.82,0) {\v}; }
  \node[font=\small, anchor=west] at (-2.3,-0.9) {suffix:};
  \node[font=\small\ttfamily, anchor=west] at (-0.3,-0.9) {a\;\; ana\;\; anana\;\; banana\;\; na\;\; nana};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.0,-1.4) {sorted suffixes -> every substring is a prefix of some suffix};
\end{tikzpicture}

Pattern search with a suffix array

Because suffixes are sorted, searching for a pattern p is a binary search (Chapter 8): compare p against the suffix at the midpoint.

def search(s, sa, pattern):
    lo, hi = 0, len(sa) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        suffix = s[sa[mid]:sa[mid] + len(pattern)]
        if suffix == pattern:
            return sa[mid]
        if suffix < pattern:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Each comparison is \(O(m)\) for pattern length \(m\), and there are \(O(\log n)\) of them: \(O(m \log n)\) per search, using \(O(n)\) space. Once built, the suffix array answers many queries cheaply.

The LCP array: shared prefixes

The Longest Common Prefix array stores, for each adjacent pair in the suffix array, the length of their common prefix.

def lcp_array(s, sa):
    rank = {pos: i for i, pos in enumerate(sa)}
    lcp, k = [0] * len(s), 0
    for i in range(len(s)):
        if rank[i] == 0:
            continue
        j = sa[rank[i] - 1]
        while i + k < len(s) and j + k < len(s) and s[i + k] == s[j + k]:
            k += 1
        lcp[rank[i]] = k
        if k:
            k -= 1
    return lcp

Kasai’s algorithm computes it in \(O(n)\) by reusing the previous overlap. The LCP array is what makes suffix-structure problems practical.

The classic suffix problems

Longest repeated substring — the maximum value in the LCP array. Two suffixes that share a long prefix are a long repeated substring.

def longest_repeated_substring(s):
    sa = build_suffix_array(s)
    lcp = lcp_array(s, sa)
    length = max(lcp)
    start = sa[lcp.index(length)]
    return s[start:start + length]

print(longest_repeated_substring("banana"))   # "ana"

Number of distinct substrings — total substrings minus repeats: \(\frac{n(n+1)}{2} - \sum \text{lcp}[i]\), each suffix contributes its length minus the prefix already counted.

Longest common substring of two strings — concatenate with a separator, build the suffix array, and take the maximum LCP between a suffix from each string.

Longest common prefix of queries — a range-minimum query on the LCP array gives the LCP of any two suffixes.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.7cm, minimum height=0.6cm, font=\small}]
  \foreach \v [count=\i from 0] in {a,ana,anana,banana,na,nana} {
    \node[c, fill=blue!8, font=\ttfamily\small] at (\i*0.82,0) {\v};
  }
  \node[font=\small\ttfamily, anchor=west] at (-0.9,-0.75) {LCP:\;\; 0\;\; 1\;\; 3\;\; 0\;\; 0\;\; 2};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (2.0,-1.2) {max LCP = 3 -> "ana" repeats};
\end{tikzpicture}

Suffix tree: the compressed trie

A suffix tree is a compressed trie of all suffixes: chains of single-child nodes are collapsed into edges labelled with substrings. It has \(O(n)\) nodes, and every substring is a prefix of a path. Operations become:

Suffix trees are powerful but fiddly to implement (Ukkonen’s algorithm). In practice, most engineers use a suffix array + LCP and get the same asymptotics with far less code and memory. Suffix automata and the FM-index are other linear-space alternatives used in bioinformatics and search engines.

Structure Space Build Pattern search
Suffix array + LCP \(O(n)\) \(O(n \log n)\) \(O(m \log n)\)
Suffix tree \(O(n)\) \(O(n)\) \(O(m)\)
Naive suffix list \(O(n^2)\) \(O(n^2)\) \(O(m)\)

Constructing a suffix array

The straightforward method sorts the suffixes with a comparison sort, but naive comparison is \(O(n \log n)\) comparisons of \(O(n)\) strings — \(O(n^2 \log n)\) worst case. The efficient approach uses doubling: sort by the first character, then by the first two, four, eight characters (each step sorts pairs of previously computed ranks), giving \(O(n \log n)\).

def build_suffix_array(s):
    n = len(s)
    sa = list(range(n))
    rank = list(map(ord, s))
    k = 1
    while k < n:
        sa.sort(key=lambda i: (rank[i], rank[i + k] if i + k < n else -1))
        tmp = [0] * n
        for i in range(1, n):
            a, b = sa[i - 1], sa[i]
            tmp[b] = tmp[a] + ((rank[a], rank[a + k] if a + k < n else -1) <
                               (rank[b], rank[b + k] if b + k < n else -1))
        rank = tmp
        if rank[sa[-1]] == n - 1:
            break
        k *= 2
    return sa

You rarely implement this in an interview; knowing the structure, its cost, and the LCP-based problems is what matters.

Pitfalls

QQuestionSelf-check

Why does a suffix array use \(O(n)\) space while the substrings number \(O(n^2)\)? How do you find the longest repeated substring?

ASolution

It stores only the starting indices of the \(n\) suffixes in sorted order, relying on the original string for the characters; every substring is a prefix of some suffix, so the ordering captures all of them. The longest repeated substring is the maximum value in the LCP array, which gives the longest shared prefix of two adjacent sorted suffixes.

Next: Skip Lists and Indexing (DSA #19) — probabilistic balance, and how databases find rows fast.