AlgoTales · Roadmap

Suffix array

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

Where you will meet this in real life

A suffix array lists the starting positions of all tails of a text in dictionary order. Because all tails that begin with the same pattern sit next to each other, you can find a pattern by a quick halving search instead of scanning the text.

Practical use cases

  • Web app: Full-text search inside a big document set. A legal or documentation site lets users search any phrase inside millions of characters of text. With the sorted tails prepared in advance, each search halves the list again and again, so results appear in a few dozen steps instead of reading all of the text.
  • Web app: Find repeated phrases in a manuscript. An editing tool highlights the longest phrase that appears twice in a long article. In the sorted tails, neighbours share beginnings, so comparing neighbours reveals repeats without checking all pairs.
  • System: Genome indexes and compression. Searching a genome without scanning it, and compression programs that spot repeated chunks, depend on sorted tails to jump straight to matches. Such tools prepare the sorted positions once, then answer thousands of different search questions without rereading the original text.

The story: Mira's Tail-End Dictionary

The school library had one gigantic book with no gaps: a single endless line of letters from a lost diary. People asked, "Does the word ana appear in it? How many times?" Scanning the whole book every time took forever, and the librarian was tired.

Mira had a bright idea: "Let us cut the book at every position, keeping the tail end from there to the very end. Each cut tail is called a suffix. Then sort all the tails like words in a dictionary." In a sorted dictionary, all entries that begin with "ana" sit in one neat block, side by side!

The tails themselves would be far too big to write out, so she only wrote down where each tail starts, in sorted order. That short list of start positions is the suffix array. To find "ana" she opened it in the middle, compared, and halved the pile again and again, just like looking up a word in a dictionary. How to sort the tails quickly? She sorted by the first letter, then by the first two, then four, then eight, doubling each time, reusing the last round's ranks.

How to spot this problem, and where you need it

You need to search for many different patterns in the same big text, and scanning the whole text for every search is too slow.

Signs you need it

  • The text is fixed (a book, a genome, a log archive) while patterns vary from one request to the next.
  • Each search currently reads the entire text, and there are thousands of searches.
  • The problem asks for repeated substrings, number of distinct substrings or "substring search with preprocessing".
  • You can afford a one-time preparation step and extra memory.

Where to use it in a project

  • Search over large static text collections such as manuals, archives and genomes.
  • Tools that find repeats, such as duplicate paragraphs or common phrases.

The solution

Write down every tail of the text by its starting position and sort the tails in dictionary order; store only the sorted list of positions. To search for a pattern, do a halving search over that list, comparing the pattern with the tail at the middle position each time. All matches sit together in one block of the list.

Payoff: Before: reading the whole text for every search. After: about 20 comparisons for a text with a million letters.

Explain it like I am 8

Write every tail of a word on its own card: banana, anana, nana, ana, na, a. Sort the cards in dictionary order and write down only the start numbers. Now to find a word, you flip to the right part of the card pile quickly, because all cards starting the same way are neighbours.

How it works, step by step

  1. List every suffix (the word from each start position to the end).
  2. Sort them in dictionary order, but remember only their start positions: that list is the suffix array SA.
  3. To build it fast, use prefix doubling: rank every position by its first letter, then by its first 2 letters (pair of ranks), then 4, 8... until all ranks differ.
  4. To search a pattern, binary search the array comparing the pattern with the first few letters of each suffix.
  5. The block of suffixes that start with the pattern gives all the match positions (count = block size).

The code in four languages

PHP

<?php
// Suffix array by prefix doubling: rank by 1 letter, then 2, then 4, ...
function suffixArray(string $s): array {
    $n = strlen($s);
    if ($n === 0) return [];
    $sa = range(0, $n - 1);
    $rank = [];
    for ($i = 0; $i < $n; $i++) $rank[$i] = ord($s[$i]);
    for ($k = 1; ; $k *= 2) {
        $key = fn($i) => [$rank[$i], $i + $k < $n ? $rank[$i + $k] : -1];
        usort($sa, function ($a, $b) use ($key) {
            $x = $key($a); $y = $key($b);
            return $x[0] <=> $y[0] ?: $x[1] <=> $y[1];
        });
        $tmp = [$sa[0] => 0];
        for ($i = 1; $i < $n; $i++) {
            $tmp[$sa[$i]] = $tmp[$sa[$i - 1]] + ($key($sa[$i - 1]) !== $key($sa[$i]) ? 1 : 0);
        }
        $rank = $tmp;
        if ($rank[$sa[$n - 1]] === $n - 1 || $k >= $n) break;   // all ranks distinct
    }
    return $sa;
}
// All start positions of $p, using binary search on the array.
function saFind(string $s, array $sa, string $p): array {
    $n = count($sa); $m = strlen($p);
    $lo = 0; $hi = $n;
    while ($lo < $hi) {                                   // first suffix >= p
        $mid = intdiv($lo + $hi, 2);
        if (strcmp(substr($s, $sa[$mid], $m), $p) < 0) $lo = $mid + 1; else $hi = $mid;
    }
    $start = $lo; $hi = $n;
    while ($lo < $hi) {                                   // first suffix > p (by its first m letters)
        $mid = intdiv($lo + $hi, 2);
        if (strcmp(substr($s, $sa[$mid], $m), $p) <= 0) $lo = $mid + 1; else $hi = $mid;
    }
    $res = array_slice($sa, $start, $lo - $start);
    sort($res);
    return $res;
}
$s = "banana";
$sa = suffixArray($s);
echo implode(",", $sa), "\n";                              // 5,3,1,0,4,2
echo implode(",", saFind($s, $sa, "ana")), "\n";           // 1,3

JavaScript

// Suffix array by prefix doubling: rank by 1 letter, then 2, then 4, ...
function suffixArray(s) {
  const n = s.length;
  if (n === 0) return [];
  const sa = [...Array(n).keys()];
  let rank = [...s].map(c => c.charCodeAt(0));
  for (let k = 1; ; k *= 2) {
    const key = i => [rank[i], i + k < n ? rank[i + k] : -1];
    sa.sort((a, b) => {
      const x = key(a), y = key(b);
      return (x[0] - y[0]) || (x[1] - y[1]);
    });
    const tmp = new Array(n);
    tmp[sa[0]] = 0;
    for (let i = 1; i < n; i++) {
      const x = key(sa[i - 1]), y = key(sa[i]);
      tmp[sa[i]] = tmp[sa[i - 1]] + (x[0] !== y[0] || x[1] !== y[1] ? 1 : 0);
    }
    rank = tmp;
    if (rank[sa[n - 1]] === n - 1 || k >= n) break;     // all ranks distinct
  }
  return sa;
}
// All start positions of p, using binary search on the array.
function saFind(s, sa, p) {
  const n = sa.length, m = p.length;
  let lo = 0, hi = n;
  while (lo < hi) {                                     // first suffix >= p
    const mid = (lo + hi) >> 1;
    if (s.substr(sa[mid], m) < p) lo = mid + 1; else hi = mid;
  }
  const start = lo; hi = n;
  while (lo < hi) {                                     // first suffix > p (by its first m letters)
    const mid = (lo + hi) >> 1;
    if (s.substr(sa[mid], m) <= p) lo = mid + 1; else hi = mid;
  }
  return sa.slice(start, lo).sort((a, b) => a - b);
}
const s = "banana";
const sa = suffixArray(s);
console.log(sa.join(","));                              // 5,3,1,0,4,2
console.log(saFind(s, sa, "ana").join(","));            // 1,3

Java

import java.util.*;

public class Main {
    // Rank of suffix i for the current doubling step: (rank of first k letters, rank of next k letters).
    static long key(int[] rank, int i, int k, int n) {
        long second = i + k < n ? rank[i + k] : -1;
        return (long) rank[i] * 1_000_000 + (second + 1);
    }

    // Suffix array by prefix doubling: rank by 1 letter, then 2, then 4, ...
    static Integer[] suffixArray(String s) {
        int n = s.length();
        if (n == 0) return new Integer[0];
        Integer[] sa = new Integer[n];
        int[] rank = new int[n];
        for (int i = 0; i < n; i++) { sa[i] = i; rank[i] = s.charAt(i); }
        for (int k = 1; ; k *= 2) {
            final int step = k;
            final int[] cur = rank;
            Arrays.sort(sa, Comparator.comparingLong(i -> key(cur, i, step, n)));
            int[] tmp = new int[n];
            tmp[sa[0]] = 0;
            for (int i = 1; i < n; i++) {
                boolean differs = key(cur, sa[i - 1], k, n) != key(cur, sa[i], k, n);
                tmp[sa[i]] = tmp[sa[i - 1]] + (differs ? 1 : 0);
            }
            rank = tmp;
            if (rank[sa[n - 1]] == n - 1 || k >= n) break;      // all ranks distinct
        }
        return sa;
    }

    // The first m letters of the suffix starting at i.
    static String head(String s, int i, int m) {
        return s.substring(i, Math.min(s.length(), i + m));
    }

    // All start positions of p, using binary search on the array.
    static List<Integer> saFind(String s, Integer[] sa, String p) {
        int n = sa.length, m = p.length();
        int lo = 0, hi = n;
        while (lo < hi) {                                       // first suffix >= p
            int mid = (lo + hi) / 2;
            if (head(s, sa[mid], m).compareTo(p) < 0) lo = mid + 1; else hi = mid;
        }
        int start = lo;
        hi = n;
        while (lo < hi) {                                       // first suffix > p (by its first m letters)
            int mid = (lo + hi) / 2;
            if (head(s, sa[mid], m).compareTo(p) <= 0) lo = mid + 1; else hi = mid;
        }
        List<Integer> res = new ArrayList<>(Arrays.asList(sa).subList(start, lo));
        Collections.sort(res);
        return res;
    }

    public static void main(String[] args) {
        String s = "banana";
        Integer[] sa = suffixArray(s);
        System.out.println(Arrays.toString(sa));                // [5, 3, 1, 0, 4, 2]
        System.out.println(saFind(s, sa, "ana"));               // [1, 3]
    }
}

Go

package main

import (
	"fmt"
	"sort"
)

// suffixArray builds the array by prefix doubling: rank by 1 letter, then 2, then 4, ...
func suffixArray(s string) []int {
	n := len(s)
	if n == 0 {
		return []int{}
	}
	sa := make([]int, n)
	rank := make([]int, n)
	for i := 0; i < n; i++ {
		sa[i] = i
		rank[i] = int(s[i])
	}
	for k := 1; ; k *= 2 {
		// key(i) = (rank of first k letters, rank of the next k letters)
		key := func(i int) [2]int {
			if i+k < n {
				return [2]int{rank[i], rank[i+k]}
			}
			return [2]int{rank[i], -1}
		}
		sort.Slice(sa, func(a, b int) bool {
			x, y := key(sa[a]), key(sa[b])
			if x[0] != y[0] {
				return x[0] < y[0]
			}
			return x[1] < y[1]
		})
		tmp := make([]int, n)
		tmp[sa[0]] = 0
		for i := 1; i < n; i++ {
			tmp[sa[i]] = tmp[sa[i-1]]
			if key(sa[i-1]) != key(sa[i]) {
				tmp[sa[i]]++
			}
		}
		rank = tmp
		if rank[sa[n-1]] == n-1 || k >= n { // all ranks distinct
			break
		}
	}
	return sa
}

// head returns the first m letters of the suffix starting at i.
func head(s string, i, m int) string {
	return s[i:min(len(s), i+m)]
}

// saFind lists all start positions of p, using binary search on the array.
func saFind(s string, sa []int, p string) []int {
	n, m := len(sa), len(p)
	lo, hi := 0, n
	for lo < hi { // first suffix >= p
		mid := (lo + hi) / 2
		if head(s, sa[mid], m) < p {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	start := lo
	hi = n
	for lo < hi { // first suffix > p (by its first m letters)
		mid := (lo + hi) / 2
		if head(s, sa[mid], m) <= p {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	res := append([]int{}, sa[start:lo]...)
	sort.Ints(res)
	return res
}

func main() {
	s := "banana"
	sa := suffixArray(s)
	fmt.Println(sa)                   // [5 3 1 0 4 2]
	fmt.Println(saFind(s, sa, "ana")) // [1 3]
}

Time: O(n log² n) to build, O(m log n) per search · Extra space: O(n). Doubling needs about log n rounds of sorting; with radix sort it drops to O(n log n), and special methods reach O(n).

Watch out for

  • Storing the actual suffix strings: that takes far too much memory. Store only start positions.
  • Forgetting that a suffix shorter than the pattern may sort before it; compare only the first m letters.
  • Treating the missing second rank as 0 in doubling. Use -1 so shorter suffixes sort first.

Quick check

  1. What does the suffix array of "banana" contain?
    • The sorted letters
    • The start positions of all suffixes in sorted order
    • The longest repeated substring
  2. Why can we binary search for a pattern?
    • Suffixes are sorted so matches form one block
    • Letters are numbers
    • The array is small
  3. In prefix doubling, after round k each suffix is ranked by its first ... letters.
    • k
    • 2k
    • n