AlgoTales · Roadmap

Suffix tree

Advanced · 14 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A suffix tree is a branching map built from every possible ending of a piece of text, so that any word inside the text can be found by simply following letters down a path. It is worth knowing because it turns "search this huge text again and again" into very quick lookups.

Practical use cases

  • Web app: Search inside a huge knowledge-base article. A support portal stores one giant manual and agents search it for phrases like "refund failed". Scanning the whole manual for each search makes the box lag. Building a suffix tree once lets each phrase be found by walking its letters, so the result shows as the agent types, no matter how long the manual is.
  • Web app: Plagiarism check on student submissions. A college portal wants to show the longest stretch of text two assignments share. Comparing them character by character from every starting point takes minutes for long essays. A suffix tree built over both essays exposes the longest shared stretch directly, so the report appears in seconds after upload.
  • Web app: Highlighting every match in a document viewer. A browser-based document viewer must light up every spot where the search word appears in a 500-page text. With a suffix tree, one walk down the word's letters gives all the places at once, instead of rescanning the pages for each new word the user types.
  • System: Genome and bioinformatics search. DNA is a text with millions of letters. Labs build a suffix tree once and then check thousands of short gene patterns against it, and each answer depends only on how long the pattern is, not on how long the genome is.

The story: The Banyan Tree of Endings

In Kabir's village stood an ancient banyan whose branches told stories. Kabir wondered: "What if I hang every ending of a word on a tree, so that any piece of the word can be found by simply walking down from the roots?" For the word BANANA he would hang the endings: banana, anana, nana, ana, na, a.

Written naively, that tree would be a thick forest with a separate thin twig for every letter. Mira trimmed it: "When a branch has no fork for a long stretch, squash the whole stretch into one edge with a label." Now an edge could carry "banana" or "na" in one go. When two endings share a beginning, like "ana" and "anana", their branch is shared and only splits where they become different.

To make sure every ending finishes on a leaf, they glued a special stop sign $ at the end of the word. Now looking for any piece is just walking from the root, spelling letters down edges. If you arrive, the piece exists, and the leaves under that spot tell all positions where it occurs! This is the suffix tree: lightning-fast substring questions, at the price of a heavy tree (and a very clever linear-time builder called Ukkonen's algorithm).

How to spot this problem, and where you need it

You have one big text that stays the same, and you must answer many substring questions about it (does this word appear, where, what is the longest shared part), and rescanning it each time is too slow.

Signs you need it

  • The same large string is searched again and again with different patterns, and each search uses a full str-contains or strpos scan from the start.
  • The problem asks for the longest common substring, the number of different substrings, or "does this pattern occur anywhere" for many patterns.
  • Search is fine on short text but each query gets slower as the document or file grows, even though the text never changes.
  • You find yourself writing nested loops that try every starting position against every other starting position.

Where to use it in a project

  • A document or log search feature where the text is loaded once and then queried many times by different users.
  • A similarity or plagiarism report that must find the longest passage shared by two uploaded files.
  • A bioinformatics or text-analysis tool that checks many short patterns against one very long sequence.

The solution

Write down every ending of the text (for banana: banana, anana, nana, ana, na, a). Merge endings that start with the same letters into shared branches, so you get a tree where each path from the top spells part of the text. To search, follow the pattern letter by letter from the top; if you can walk the whole pattern, it exists, and everything below that point lists where. Build the tree once, then reuse it for every question.

Payoff: Before: scanning 5 million characters for each of 1,000 searches. After: one build, then each search touches only as many steps as the word has letters.

Explain it like I am 8

Imagine a tree where every path from the roots spells a tail of the word. To check whether "ana" is inside "banana", you just walk from the roots following the letters. If the path exists, it is in the word, and the leaves below tell you where.

How it works, step by step

  1. Add a unique stop mark such as $ to the end of the word so no tail is the beginning of another.
  2. Start with an empty root. Insert the suffixes one by one: s[0..], s[1..], s[2..], and so on.
  3. To insert a suffix, walk from the root along edges whose first letter matches. If an edge matches only partway, split it at the point of difference and add a new leaf for the rest.
  4. If there is no edge for the next letter, hang the whole remaining piece as a new leaf and remember the suffix's start position there.
  5. Search: walk the pattern down the edges. If you can spell it all, the leaves below that spot are all its occurrences.

The code in four languages

PHP

<?php
// A simple (slow but clear) suffix tree: insert each suffix, splitting edges when needed.
class SNode {
    public array $kids = [];     // first letter => [edge label, child node]
    public int $leaf = -1;       // start of the suffix if this is a leaf
}
function buildSuffixTree(string $s): SNode {
    $s .= "$";                                   // unique end mark
    $root = new SNode();
    for ($idx = 0; $idx < strlen($s); $idx++) {
        $suf = substr($s, $idx);
        $node = $root; $i = 0;
        while (true) {
            $c = $suf[$i];
            if (!isset($node->kids[$c])) {       // no edge: hang a new leaf
                $leaf = new SNode(); $leaf->leaf = $idx;
                $node->kids[$c] = [substr($suf, $i), $leaf];
                break;
            }
            [$label, $child] = $node->kids[$c];
            $k = 0;
            while ($k < strlen($label) && $i + $k < strlen($suf) && $label[$k] === $suf[$i + $k]) $k++;
            if ($k === strlen($label)) { $node = $child; $i += $k; continue; }   // edge fully matched
            $mid = new SNode();                  // split the edge at k
            $mid->kids[$label[$k]] = [substr($label, $k), $child];
            $leaf = new SNode(); $leaf->leaf = $idx;
            $mid->kids[$suf[$i + $k]] = [substr($suf, $i + $k), $leaf];
            $node->kids[$c] = [substr($label, 0, $k), $mid];
            break;
        }
    }
    return $root;
}
function leavesUnder(SNode $n, array &$out): void {
    if ($n->leaf >= 0) $out[] = $n->leaf;
    foreach ($n->kids as [, $child]) leavesUnder($child, $out);
}
function stFind(SNode $root, string $p): array {
    $node = $root; $i = 0; $m = strlen($p);
    while ($i < $m) {
        if (!isset($node->kids[$p[$i]])) return [];
        [$label, $child] = $node->kids[$p[$i]];
        $k = 0;
        while ($k < strlen($label) && $i < $m) {
            if ($label[$k] !== $p[$i]) return [];   // mismatch inside an edge
            $k++; $i++;
        }
        $node = $child;
    }
    $out = [];
    leavesUnder($node, $out);
    sort($out);
    return $out;
}
$tree = buildSuffixTree("banana");
echo implode(",", stFind($tree, "ana")), "\n";     // 1,3
echo implode(",", stFind($tree, "na")), "\n";      // 2,4
echo count(stFind($tree, "nab")), "\n";            // 0

JavaScript

// A simple (slow but clear) suffix tree: insert each suffix, splitting edges when needed.
class SNode {
  constructor() { this.kids = new Map(); this.leaf = -1; }   // first letter => [edge label, child]
}
function buildSuffixTree(str) {
  const s = str + "$";                          // unique end mark
  const root = new SNode();
  for (let idx = 0; idx < s.length; idx++) {
    const suf = s.slice(idx);
    let node = root, i = 0;
    for (;;) {
      const c = suf[i];
      if (!node.kids.has(c)) {                  // no edge: hang a new leaf
        const leaf = new SNode(); leaf.leaf = idx;
        node.kids.set(c, [suf.slice(i), leaf]);
        break;
      }
      const [label, child] = node.kids.get(c);
      let k = 0;
      while (k < label.length && i + k < suf.length && label[k] === suf[i + k]) k++;
      if (k === label.length) { node = child; i += k; continue; }   // edge fully matched
      const mid = new SNode();                  // split the edge at k
      mid.kids.set(label[k], [label.slice(k), child]);
      const leaf = new SNode(); leaf.leaf = idx;
      mid.kids.set(suf[i + k], [suf.slice(i + k), leaf]);
      node.kids.set(c, [label.slice(0, k), mid]);
      break;
    }
  }
  return root;
}
function leavesUnder(n, out) {
  if (n.leaf >= 0) out.push(n.leaf);
  for (const [, child] of n.kids.values()) leavesUnder(child, out);
}
function stFind(root, p) {
  let node = root, i = 0;
  while (i < p.length) {
    if (!node.kids.has(p[i])) return [];
    const [label, child] = node.kids.get(p[i]);
    let k = 0;
    while (k < label.length && i < p.length) {
      if (label[k] !== p[i]) return [];         // mismatch inside an edge
      k++; i++;
    }
    node = child;
  }
  const out = [];
  leavesUnder(node, out);
  return out.sort((a, b) => a - b);
}
const tree = buildSuffixTree("banana");
console.log(stFind(tree, "ana").join(","));     // 1,3
console.log(stFind(tree, "na").join(","));      // 2,4
console.log(stFind(tree, "nab").length);        // 0

Java

import java.util.*;

public class Main {
    // An edge carries a label (a piece of text) down to a child node.
    record Edge(String label, SNode child) {}

    static class SNode {
        Map<Character, Edge> kids = new TreeMap<>();   // first letter => edge
        int leaf = -1;                                 // start of the suffix if this is a leaf
    }

    // A simple (slow but clear) suffix tree: insert each suffix, splitting edges when needed.
    static SNode buildSuffixTree(String str) {
        String s = str + "$";                          // unique end mark
        SNode root = new SNode();
        for (int idx = 0; idx < s.length(); idx++) {
            String suf = s.substring(idx);
            SNode node = root;
            int i = 0;
            while (true) {
                char c = suf.charAt(i);
                if (!node.kids.containsKey(c)) {       // no edge: hang a new leaf
                    SNode leaf = new SNode();
                    leaf.leaf = idx;
                    node.kids.put(c, new Edge(suf.substring(i), leaf));
                    break;
                }
                Edge e = node.kids.get(c);
                String label = e.label();
                int k = 0;
                while (k < label.length() && i + k < suf.length() && label.charAt(k) == suf.charAt(i + k)) k++;
                if (k == label.length()) { node = e.child(); i += k; continue; }   // edge fully matched
                SNode mid = new SNode();               // split the edge at k
                mid.kids.put(label.charAt(k), new Edge(label.substring(k), e.child()));
                SNode leaf = new SNode();
                leaf.leaf = idx;
                mid.kids.put(suf.charAt(i + k), new Edge(suf.substring(i + k), leaf));
                node.kids.put(c, new Edge(label.substring(0, k), mid));
                break;
            }
        }
        return root;
    }

    static void leavesUnder(SNode n, List<Integer> out) {
        if (n.leaf >= 0) out.add(n.leaf);
        for (Edge e : n.kids.values()) leavesUnder(e.child(), out);
    }

    static List<Integer> stFind(SNode root, String p) {
        SNode node = root;
        int i = 0;
        while (i < p.length()) {
            Edge e = node.kids.get(p.charAt(i));
            if (e == null) return List.of();
            String label = e.label();
            int k = 0;
            while (k < label.length() && i < p.length()) {
                if (label.charAt(k) != p.charAt(i)) return List.of();   // mismatch inside an edge
                k++; i++;
            }
            node = e.child();
        }
        List<Integer> out = new ArrayList<>();
        leavesUnder(node, out);
        Collections.sort(out);
        return out;
    }

    public static void main(String[] args) {
        SNode tree = buildSuffixTree("banana");
        System.out.println(stFind(tree, "ana"));        // [1, 3]
        System.out.println(stFind(tree, "na"));         // [2, 4]
        System.out.println(stFind(tree, "nab").size()); // 0
    }
}

Go

package main

import (
	"fmt"
	"sort"
)

// Edge carries a label (a piece of text) down to a child node.
type Edge struct {
	label string
	child *SNode
}

type SNode struct {
	kids map[byte]*Edge // first letter => edge
	leaf int            // start of the suffix if this is a leaf, else -1
}

func newNode() *SNode { return &SNode{kids: map[byte]*Edge{}, leaf: -1} }

// buildSuffixTree is simple (slow but clear): insert each suffix, splitting edges when needed.
func buildSuffixTree(str string) *SNode {
	s := str + "$" // unique end mark
	root := newNode()
	for idx := 0; idx < len(s); idx++ {
		suf := s[idx:]
		node, i := root, 0
		for {
			c := suf[i]
			e, ok := node.kids[c]
			if !ok { // no edge: hang a new leaf
				leaf := newNode()
				leaf.leaf = idx
				node.kids[c] = &Edge{suf[i:], leaf}
				break
			}
			k := 0
			for k < len(e.label) && i+k < len(suf) && e.label[k] == suf[i+k] {
				k++
			}
			if k == len(e.label) { // edge fully matched
				node = e.child
				i += k
				continue
			}
			mid := newNode() // split the edge at k
			mid.kids[e.label[k]] = &Edge{e.label[k:], e.child}
			leaf := newNode()
			leaf.leaf = idx
			mid.kids[suf[i+k]] = &Edge{suf[i+k:], leaf}
			node.kids[c] = &Edge{e.label[:k], mid}
			break
		}
	}
	return root
}

func leavesUnder(n *SNode, out *[]int) {
	if n.leaf >= 0 {
		*out = append(*out, n.leaf)
	}
	for _, e := range n.kids {
		leavesUnder(e.child, out)
	}
}

func stFind(root *SNode, p string) []int {
	node, i := root, 0
	for i < len(p) {
		e, ok := node.kids[p[i]]
		if !ok {
			return nil
		}
		k := 0
		for k < len(e.label) && i < len(p) {
			if e.label[k] != p[i] { // mismatch inside an edge
				return nil
			}
			k++
			i++
		}
		node = e.child
	}
	var out []int
	leavesUnder(node, &out)
	sort.Ints(out)
	return out
}

func main() {
	tree := buildSuffixTree("banana")
	fmt.Println(stFind(tree, "ana"))      // [1 3]
	fmt.Println(stFind(tree, "na"))       // [2 4]
	fmt.Println(len(stFind(tree, "nab"))) // 0
}

Time: O(n²) for this simple build; O(n) with Ukkonen's algorithm. Search O(m + matches) · Extra space: O(n). The tree has at most about 2n nodes because long runs are squashed into labelled edges; the simple builder just takes longer to make it.

Watch out for

  • Skipping the end mark $: then a suffix like "a" ends in the middle of a branch and has no leaf.
  • Not splitting an edge when a new suffix only matches part of its label.
  • Storing every edge label as a copy of the text; real implementations store just (start, end) positions to save memory.

Quick check

  1. What does a path from the root to a leaf spell?
    • A random word
    • One suffix of the word (with the end mark)
    • The longest palindrome
  2. How do we count how many times a pattern occurs?
    • Count the leaves below the spot where the pattern ends
    • Count the edges
    • Count the root's children
  3. Why do we add the end mark $?
    • To make the word longer
    • So no suffix is a beginning of another and each ends in its own leaf
    • To sort suffixes