AlgoTales · Roadmap

Aho-Corasick

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

Where you will meet this in real life

Aho-Corasick searches a text for a whole list of keywords at once, reading the text a single time. It builds a trie of the keywords and adds shortcut links so that after a mismatch it jumps to the best continuing place instead of going back.

Practical use cases

  • Web app: Blocking banned words in chat. A live chat has a list of 5,000 banned words and every message must be checked before it appears. Searching each word separately would be slow. One pass through the message with the shortcut map flags any banned word in the time it takes to read the message.
  • Web app: Spam filter for comments or emails. A blog or mail system scans every incoming comment for hundreds of spam phrases. All phrases are matched together in one pass, so comment posting stays quick even during a spam wave. The site stays responsive because the scan time depends only on the length of the comment, not on how many phrases are listed.
  • System: Antivirus, fgrep and DNA motifs. Antivirus scanners look for many virus signatures, the fgrep tool searches for several words at once, and gene tools search many motifs, all based on this one-pass multi-keyword idea. They all rely on the same trick: build one map of all keywords once, then read each file or text only a single time.

The story: The Wedding Gate Guard

At Zoya's cousin's wedding the gate guard held a list of troublemakers' names and the cook's secret words (the guests were not to say them in front of the video team). Four bad words, and a never-ending flow of chatter. Checking each word separately against all the chatter meant the guard was listening four times over.

"Listen once," said Mira. She joined all four words into a single letter tree (a trie), so a letter walks down for all words at the same time. But when a walk dies, say after "sh" there is no more path, the guard would normally start over and miss the next word already hidden in what she heard. So Mira gave every spot in the tree a shortcut: "if you get stuck here, jump to the longest ending of what you have heard that is still the start of a word."

With the shortcuts (called fail links, a cousin of KMP's fallback table) the guard walked forward along the chatter exactly once. At every letter she stood on one spot of the tree, and the shortcuts also told her which shorter words had just ended inside the longer one: reaching "she" also means "he" was said. This is the Aho-Corasick automaton: search for many words together in one pass.

How to spot this problem, and where you need it

You must find any of many keywords inside text, and looping over every keyword for every text makes the check too slow as the keyword list grows.

Signs you need it

  • You have a list of banned words, signatures or keywords (hundreds or thousands) and lots of text to scan.
  • Your code does a foreach over keywords with strpos on each text.
  • Doubling the keyword list roughly doubles the scan time.
  • The problem says "find all occurrences of many patterns".

Where to use it in a project

  • Chat, comment and review moderation filters on sites.
  • Spam, malware or sensitive-data (for example card number marker) scanners.

The solution

Insert all keywords into a trie. Then add for each node a "fail link" pointing to the longest shorter place in the trie that matches the end of the letters seen so far, and also remember which keywords end here. Read the text one letter at a time; on a mismatch follow fail links instead of going back, and report keywords as you pass their end nodes.

Payoff: Before: 5,000 searches per message. After: one pass, with time growing with message length only.

Explain it like I am 8

A guard with a list of secret words reads a story once. She keeps a finger on a map of word-beginnings. When the next letter does not fit, she does not go back: she jumps by a shortcut to another place on the map that still fits what she just read. At each place she also checks "did any word just finish?".

How it works, step by step

  1. Build a trie of all the pattern words, marking where each word ends.
  2. Fail links: go level by level (breadth-first). For a node, follow its parent's fail links until a node has the same next letter; that is its fail link (the top if none).
  3. Also copy outputs: a node's output list includes its own word plus everything from its fail link target, so shorter words inside longer ones are not missed.
  4. Search: keep a current node. For each text letter, while the node has no edge for it, jump along the fail link (but never move back in the text).
  5. Take the edge if it exists, then report every word in the node's output list with its position.

The code in four languages

PHP

<?php
// Aho-Corasick: find ALL words from a list inside a text in one forward pass.
function buildAho(array $words): array {
    $go = [[]]; $fail = [0]; $out = [[]];
    foreach ($words as $w) {                              // 1) trie
        $s = 0;
        for ($i = 0; $i < strlen($w); $i++) {
            $c = $w[$i];
            if (!isset($go[$s][$c])) { $go[] = []; $fail[] = 0; $out[] = []; $go[$s][$c] = count($go) - 1; }
            $s = $go[$s][$c];
        }
        $out[$s][] = $w;
    }
    $q = array_values($go[0]);                            // 2) fail links, level by level
    while ($q) {
        $u = array_shift($q);
        foreach ($go[$u] as $c => $v) {
            $f = $fail[$u];
            while ($f !== 0 && !isset($go[$f][$c])) $f = $fail[$f];
            $fail[$v] = isset($go[$f][$c]) ? $go[$f][$c] : 0;
            $out[$v] = array_merge($out[$v], $out[$fail[$v]]);   // inherit shorter words
            $q[] = $v;
        }
    }
    return [$go, $fail, $out];
}
function ahoSearch(string $text, array $words): array {
    [$go, $fail, $out] = buildAho($words);
    $s = 0; $res = [];
    for ($i = 0; $i < strlen($text); $i++) {
        $c = $text[$i];
        while ($s !== 0 && !isset($go[$s][$c])) $s = $fail[$s];   // jump, never go back in text
        if (isset($go[$s][$c])) $s = $go[$s][$c];
        foreach ($out[$s] as $w) $res[] = ($i - strlen($w) + 1) . ":" . $w;
    }
    return $res;
}
echo implode(" ", ahoSearch("ushers", ["he", "she", "his", "hers"])), "\n";   // 1:she 2:he 2:hers

JavaScript

// Aho-Corasick: find ALL words from a list inside a text in one forward pass.
function buildAho(words) {
  const go = [{}], fail = [0], out = [[]];
  for (const w of words) {                                // 1) trie
    let s = 0;
    for (const c of w) {
      if (!(c in go[s])) { go.push({}); fail.push(0); out.push([]); go[s][c] = go.length - 1; }
      s = go[s][c];
    }
    out[s].push(w);
  }
  const q = Object.values(go[0]);                         // 2) fail links, level by level
  while (q.length) {
    const u = q.shift();
    for (const c of Object.keys(go[u])) {
      const v = go[u][c];
      let f = fail[u];
      while (f !== 0 && !(c in go[f])) f = fail[f];
      fail[v] = (c in go[f]) ? go[f][c] : 0;
      out[v] = out[v].concat(out[fail[v]]);               // inherit shorter words
      q.push(v);
    }
  }
  return { go, fail, out };
}
function ahoSearch(text, words) {
  const { go, fail, out } = buildAho(words);
  let s = 0; const res = [];
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    while (s !== 0 && !(c in go[s])) s = fail[s];         // jump, never go back in text
    if (c in go[s]) s = go[s][c];
    for (const w of out[s]) res.push((i - w.length + 1) + ":" + w);
  }
  return res;
}
console.log(ahoSearch("ushers", ["he", "she", "his", "hers"]).join(" "));   // 1:she 2:he 2:hers

Java

import java.util.*;

public class Main {
    // Aho-Corasick: find ALL words from a list inside a text in one forward pass.
    static List<Map<Character, Integer>> go = new ArrayList<>();   // go[state][letter] = next state
    static List<Integer> fail = new ArrayList<>();                 // where to jump on a mismatch
    static List<List<String>> out = new ArrayList<>();             // words that end at this state

    static int newState() {
        go.add(new TreeMap<>());
        fail.add(0);
        out.add(new ArrayList<>());
        return go.size() - 1;
    }

    static void buildAho(List<String> words) {
        go.clear(); fail.clear(); out.clear();
        newState();                                                // state 0 = root
        for (String w : words) {                                   // 1) trie
            int s = 0;
            for (char c : w.toCharArray()) {
                if (!go.get(s).containsKey(c)) {
                    int created = newState();
                    go.get(s).put(c, created);
                }
                s = go.get(s).get(c);
            }
            out.get(s).add(w);
        }
        Deque<Integer> q = new ArrayDeque<>(go.get(0).values());   // 2) fail links, level by level
        while (!q.isEmpty()) {
            int u = q.poll();
            for (var e : go.get(u).entrySet()) {
                char c = e.getKey();
                int v = e.getValue();
                int f = fail.get(u);
                while (f != 0 && !go.get(f).containsKey(c)) f = fail.get(f);
                fail.set(v, go.get(f).getOrDefault(c, 0));
                out.get(v).addAll(out.get(fail.get(v)));           // inherit shorter words
                q.add(v);
            }
        }
    }

    static List<String> ahoSearch(String text, List<String> words) {
        buildAho(words);
        int s = 0;
        List<String> res = new ArrayList<>();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            while (s != 0 && !go.get(s).containsKey(c)) s = fail.get(s);   // jump, never go back in text
            if (go.get(s).containsKey(c)) s = go.get(s).get(c);
            for (String w : out.get(s)) res.add((i - w.length() + 1) + ":" + w);
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(String.join(" ", ahoSearch("ushers", List.of("he", "she", "his", "hers"))));   // 1:she 2:he 2:hers
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

// Automaton is the Aho-Corasick machine: a trie plus fail links.
type Automaton struct {
	next []map[byte]int // next[state][letter] = next state
	fail []int          // where to jump on a mismatch
	out  [][]string     // words that end at this state
}

func (a *Automaton) newState() int {
	a.next = append(a.next, map[byte]int{})
	a.fail = append(a.fail, 0)
	a.out = append(a.out, nil)
	return len(a.next) - 1
}

// buildAho finds ALL words from a list inside a text in one forward pass (after this setup).
func buildAho(words []string) *Automaton {
	a := &Automaton{}
	a.newState()              // state 0 = root
	for _, w := range words { // 1) trie
		s := 0
		for i := 0; i < len(w); i++ {
			c := w[i]
			if _, ok := a.next[s][c]; !ok {
				created := a.newState()
				a.next[s][c] = created
			}
			s = a.next[s][c]
		}
		a.out[s] = append(a.out[s], w)
	}
	// 2) fail links, level by level
	var q []int
	for _, v := range a.next[0] {
		q = append(q, v)
	}
	sort.Ints(q)
	for len(q) > 0 {
		u := q[0]
		q = q[1:]
		letters := make([]int, 0, len(a.next[u]))
		for c := range a.next[u] {
			letters = append(letters, int(c))
		}
		sort.Ints(letters)
		for _, lc := range letters {
			c := byte(lc)
			v := a.next[u][c]
			f := a.fail[u]
			for f != 0 {
				if _, ok := a.next[f][c]; ok {
					break
				}
				f = a.fail[f]
			}
			a.fail[v] = a.next[f][c]                         // 0 when there is no such edge
			a.out[v] = append(a.out[v], a.out[a.fail[v]]...) // inherit shorter words
			q = append(q, v)
		}
	}
	return a
}

func ahoSearch(text string, words []string) []string {
	a := buildAho(words)
	s := 0
	var res []string
	for i := 0; i < len(text); i++ {
		c := text[i]
		for s != 0 {
			if _, ok := a.next[s][c]; ok {
				break
			}
			s = a.fail[s] // jump, never go back in text
		}
		if nxt, ok := a.next[s][c]; ok {
			s = nxt
		}
		for _, w := range a.out[s] {
			res = append(res, fmt.Sprintf("%d:%s", i-len(w)+1, w))
		}
	}
	return res
}

func main() {
	fmt.Println(strings.Join(ahoSearch("ushers", []string{"he", "she", "his", "hers"}), " ")) // 1:she 2:he 2:hers
}

Time: O(n + total pattern letters + matches) · Extra space: O(total pattern letters). One forward pass over the text, no matter how many words are in the list (plus the time to print each match found).

Watch out for

  • Forgetting to inherit outputs from the fail link, so "he" is missed inside "she".
  • Building fail links in the wrong order. They must be computed level by level (breadth-first) so the shorter links already exist.
  • Moving back in the text on a mismatch. Only the node jumps; the text moves forward.

Quick check

  1. What is a fail link?
    • A pointer to the parent node
    • A jump to the longest ending that is still the start of a word
    • A pointer to the last word added
  2. Why does reaching "she" also report "he"?
    • It is a bug
    • The fail link of "she" leads to "he", whose word ends inside
    • Words are sorted
  3. Compared with running KMP once per word, Aho-Corasick...
    • reads the text once for all words
    • needs sorted words
    • only finds the first match