Version: 0.6.22

6. Prefix and Suffix Trees#

Lecture:

Lecture 5.6 (slides)

Objectives:

Understand what is a prefix and what is a suffix tree

Concepts:

Insertion, deletion and search into a Prefix-tree

Implementation:

Scala PrefixTree.scala

As a last example of tree data structures, we shall look at prefix and suffix trees. These are data structures used to speed up text search. especially full-text search and auto completion in text editors.

  • Auto-completion means that editor suggests possible endings for what you have started to type. For instance, Fig. 6.13 shows an example of “default completion”, where the editor make suggestions based on words already in the document.

  • Full-text search, is what happen for instance when you press Ctrl-F, which prompt you for a some text, and highlights all the occurrences in the page. This is often available in text editors, web browser, or IDEs.

Prefixes vs. Suffixes

What are prefixes and suffixes? Intuitively, we can say the are just “beginning” and “ending” of sequences. More formally, given a sequence of characters \(s = (c_1, c_2, \dots, c_n)\) any shorted sequence \(s' = (c_1, \dots, c_k)\) where \(0 \leq k \leq n\) is a prefix of \(S\). For instance, the word “algorithm” has the following prefixes (ordered by length):

\[P = \{ '',\, 'a',\, 'al',\, 'alg',\, 'algo',\, 'algor',\, 'algori',\, 'algorit',\, 'algorith',\, 'algorithm' \}\]

Note that the set of prefixes includes the empty sequence and the complete word itself. Formally, we denote that fact that a word \(w\) admits a prefix \(p\) by \(p \preceq w\).

Similarly, suffixes are possible endings. Formally, and sequence \(s' = (c_k, \dots, c_n)\) is a suffix of \(s\). The word algorithm therefore admits the following suffixes:

\[S = \{ '',\, 'm',\, 'hm',\, 'thm',\, 'ithm',\, 'rithm',\, 'orithm',\, 'gorithm',\, 'lgorithm', \, 'algorithm' \}\]

6.1. Prefix Trees#

How can we implement such auto-completion mechanisms efficiently? What we need is kind of Map ADT that could give us all the word that starts by the “prefix” the user has typed. For instance, given a set of words already typed, one could index them by prefix, using a hash table.

See also

📖 Goodrich, M. T., Tamassia, R., & Goldwasser, M. H. (2014). Data structures and algorithms in Java. John Wiley & Sons. Chap. 13

The conventional solution is to use a prefix tree, also known as trie. A prefix tree is not an ADT per se, but it extends the Set ADT and generally exposes the following operations:

tries.contains(t: Trie, w: Word) → Boolean#

Check whether the prefix tree \(t\) contains the given word \(w\).

Returns the subset \(S\) of all the words from \(t\) that starts with the given prefix \(p\).

Pre-conditions:
  • None

Post-conditions:
  • (A1) \(S\) is the very subset of words from the prefix tree that start with the given prefix \(p\). No other words in the tree starts with \(p\) and S does not contain any other word than those from the tree.

    \[S = \mathit{prefix\_search}(t, p) \implies S = \{ w \in \mathcal{A}^* \:|\: contains(t, w) \land p \preceq w \}\]
tries.add(t: Trie, w: Word) → Trie#

Add a new word in the prefix tree \(t\).

Pre-conditions:
  • None

Post-conditions:
  • (A2) The word is \(w\) is necessary in the resulting prefix tree, that is:

    \[t' = add(t, w) \Longleftrightarrow contains(t', w)\]
tries.remove(t: Trie, w: word) → Trie#

Remove the given word \(w\) from the the prefix tree \(t\).

Pre-conditions:
  • None

Post-conditions:
  • (A3) The word that is removed is not anymore in the result prefix tree, that is:

    \[t' = remove(t, w) \Longleftrightarrow \neg \, contains(t', w)\]

6.1.1. Basic Structure#

A prefix tree, is an \(n\)-ary tree meant to contains a set of words. Every node in the tree contains a symbol from the alphabet of these words. The root contains a special symbol \(\varepsilon\), which represents the empty symbol. The leaves carries another special symbol, \(\bot\), which denotes the end of a word. This way every path from the root to a leaf node represents a word starting from \(\varepsilon\) and ending with \(\bot\).

Fig. 6.14 shows a prefix tree built over the words: ‘apart’, ‘apartment’, ‘ape’, ‘apear’, ‘apple’, ‘apply’, ‘apricot’, ‘april’.

../../_images/prefix_tree.svg

Fig. 6.14 A prefix tree built on the set of eight words \(S = \{'apart', 'apartment', 'ape', \, 'apear',\, 'apple', 'apply',\, 'apricot',\, 'april' \}\)#

Each leaf is annotated with the word that can be read following the path from the root to that leaf. Similarly, the path that leads to an internal node represent a prefix and its descend leaves are all the words that start with that prefix.

In a sense, a node somehow represents the characters that have been typed so far by the user. On the root for instance, the user hasn’t typed anything yet and all the words are possible. As we move down along a specific path, we start narrowing down the set of possible worda. In Fig. 6.14, in Node 2, we know the user has typed an “a”, in Node 3, we know the suer has typed the prefix “ap”, in Node 4, the prefix “app”, and so on and so forth.

Why Use Special Characters?

The special characters \(\varepsilon\) and \(\bot\) allow handling words that are also a prefix of another longer word, such as ‘apart’ which is a prefix of ‘apartment’. Without the special \(\bot\) character, we would have no way to know that apart is also a valid word in the set.

6.1.2. Compressed Prefix Tree#

This default tree structure is not really efficient, because it consumes a lot memory: There are many nodes that have only one child. To reduce the memory overhead, prefix trees are compressed as follows.

We place more than one symbol in each node, and merge those nodes that have only one child, consequently. Fig. 6.15 shows the compressed version of the prefix tree initially shown on Fig. 6.14. Now, all nodes but the leaves have two or more children.

trees/tries/_static/images/compressed.svg

Fig. 6.15 A compressed prefix tree, equivalent to the one shown on Fig. 6.14#

6.1.3. Membership#

To check whether a given word \(w=(c_1,\dots,c_k)\) exists in our prefix tree, we use the following procedure (assuming a non-compressed prefix tree):

  1. We start at the root of the tree, which becomes our “current node” \(n\).

  2. If Node \(n\) is a branch

    1. If the word \(w\) is empty, we return true only if Node \(n\) has a child whose symbol is \(\bot\). This child is a leaf, which marks the end of a word.

    2. Else, if Node \(n\) has a child node \(c\) whose symbol is \(c_1\) (the first character)

      1. We remove that first character from Word \(w\)

      2. Node \(c\) becomes our current node and we continue at Step 2.

    3. Else, we return false.

  3. Otherwise (Node \(n\) is a leaf), we return true only if the given word \(w\) is empty (i.e., \(w=''\)).

Figure Fig. 6.16 illustrates how this procedure operates. It shows how the search for “ape” at the root node, reduces to searching for “pe” on the child, which reduces to searching for “e” on the grandchild, which reduces to searching for the empty word.

trees/tries/_static/images/contains.svg

Fig. 6.16 Searching for the word “ape” in the prefix tree initially shown on Fig. 6.14, shortened for the sake conciseness.#

Why Is This Correct?

Every word stored in the tree is spelled by exactly one path, from the root down to a leaf \(\bot\). Besides, the children of a node all carry distinct symbols, so, at each step, there is at most one child to follow: The procedure follows the only path that may spell \(w\). It reaches the end of that path (i.e., the word is empty) and finds a \(\bot\) leaf if and only if \(w\) was added to the tree. In particular, a prefix of a stored word is not found (unless it was added too): There is a path for it, but it does not end with a \(\bot\) leaf.

How Efficient Is This?

Let us consider searching for a word \(w=(c_1,\ldots,c_n)\). How much time does it require? In the best case, we deduce straight in the root node that the word \(w\) is not in the tree, because the root has no children whose symbol matches its character, \(c_1\). Besides, if branch nodes are implemented using hashing, that local search runs in \(O(1)\). If it were implemented with a linear search, it would run in \(O(|\mathcal{A}|)\) where \(\mathcal{A}\) represents the alphabet over which the words are built.

What is the worse case? The worst case occurs when we search for the longest word that exists in the tree. This longest word is stored along the longest branch of the tree, and, in that case, we have to check every node along that long branch. The would give us a worst case runtime that is linear to the length of the word \(w\), that is \(O(n)\). Again if searching for specific child is implemented using a local search, then, the search would run in \(O(n \cdot |\mathcal{A}|)\)

As for the memory, the recursive implementation I showed above would require at \(O(n)\) memory, as each node would place a new call to progress further down the tree.

6.1.5. Insertion#

To add a word \(w=(c_1,\dots,c_k)\) to a prefix tree, we follow the path that spells \(w\), and we create the nodes that are missing.

  1. We start at the root of the tree, which becomes our “current node” \(n\).

  2. If the word \(w\) is empty, we add a leaf \(\bot\) to the children of Node \(n\), unless it already has one. We are done.

  3. Otherwise

    1. If Node \(n\) has no child whose symbol is \(c_1\) (the first character), we create one: A new branch with the symbol \(c_1\) and no children.

    2. We remove the first character from the word \(w\), the child whose symbol is \(c_1\) becomes our current node, and we continue at Step 2.

For example, adding “apes” to a tree that contains only “ape” follows the nodes “a”, “p” and “e”, which already exist. Node “e” has no child “s”, so we create it, and we then add a leaf \(\bot\) below it. The tree now contains both “ape” and “apes”. Adding a word that is already in the tree changes nothing, because all the nodes already exist.

How Efficient Is This?

Adding a word \(w\) visits at most one node per character, plus the leaf. If branch nodes are implemented using hashing, each step runs in \(O(1)\), and the insertion runs in \(O(|w|)\). It does not depend on the number of words already in the tree. With a linear search among the children, we would get \(O(|w| \cdot |\mathcal{A}|)\).

6.1.6. Deletion#

To remove a word \(w=(c_1,\dots,c_k)\) from a prefix tree, we follow the path that spells \(w\), remove its leaf \(\bot\), and then we clean up the nodes that are no longer useful.

  1. We start at the root of the tree, which becomes our “current node” \(n\).

  2. If the word \(w\) is empty, we remove the leaf \(\bot\) from the children of Node \(n\) (if there is one).

  3. Otherwise, if Node \(n\) has a child \(c\) whose symbol is \(c_1\) (the first character)

    1. We remove the first character from the word \(w\), and we remove the remaining word from Node \(c\) (we continue at Step 2, with \(c\) as our current node).

    2. Once this is done, if Node \(c\) has no children left, we remove it from the children of Node \(n\).

  4. Else (there is no such child), the word is not in the tree, and nothing changes.

The clean-up of Step 3.b is important, because nodes are shared between words. We can only remove a node if it is not on the path of another word, that is, if it has no children left. For example, if the tree contains “app” and “apple”, removing “app” only removes its leaf \(\bot\): The second “p” still has a child “l”, which is needed by “apple”. By contrast, removing “apple” removes the leaf \(\bot\) and then the nodes “e” and “l”, which have no children left. It stops at the second “p”, which still has a leaf \(\bot\) for “app”.

How Efficient Is This?

As for the insertion, removing a word \(w\) visits at most one node per character, and cleaning up happens along the same path. The deletion runs in \(O(|w|)\), if branch nodes are implemented using hashing.

6.2. Suffix Trees#

A prefix tree is great when we know how a word starts, as in auto-completion. But a full-text search, like Ctrl-F, is different: The text we look for may appear anywhere, in the middle of a word, or across several words. How can a prefix tree help with that?

6.2.1. The Text Index ADT#

Let us first state what we want. We have a text, which we will search many times, for all sorts of fragments (a fragment is simply a short \(Text\), such as a word, or part of a word). For each fragment, we want to know where it occurs in the text. A text index is a structure that answers this question. It has only two operations: One to build the index of a given text, and one to find a fragment in that text.

text_index.create(t: Text) → TextIndex#

Build an index for the given text \(t\).

Preconditions:

None

Postconditions:
  • The resulting index answers questions about the text \(t\).

text_index.find(i: TextIndex, f: Text) → Sequence[Position]#

Return the positions where the given fragment \(f\) occurs in the text of the index \(i\). The first character of the text has position 0. For instance, the fragment “ana” occurs twice in the text “banana”, at positions 1 and 3, so the result is the sequence \((1, 3)\). By contrast, the fragment “x” does not occur, so the result is the empty sequence.

Preconditions:

None

Postconditions:
  • The result contains a position \(p\) if, and only if, the fragment \(f\) starts at position \(p\) in the text.

  • The positions are sorted in increasing order.

  • The result is empty if, and only if, the fragment does not occur in the text.

Some details are worth noticing. Occurrences may overlap: In “banana”, the two occurrences of “ana” share the letter “a” at position 3. The empty fragment occurs everywhere, even at the very end of the text, so that, in “banana”, it is found at positions 0 to 6.

How could we implement this? The simplest idea is to do nothing when we create the index, and, every time we are asked to find a fragment, to scan the whole text from the beginning, comparing the fragment with the text at each position. This works, but it is slow if the text is long and we search it many times. A suffix tree does a bit of work upfront, to make every search fast.

6.2.2. Suffixes to the Rescue#

The trick is to notice that any occurrence of a fragment is the beginning of some suffix of the text. Consider the text “banana”. The fragment “nan” occurs in it, and indeed, if we cut away the first two letters (“ba”), what remains, “nana”, starts with “nan”. Whatever the fragment, we can always cut the text just before it, and the fragment is then a prefix of what remains.

A suffix tree is therefore nothing more than a prefix tree that stores all the suffixes of a text. The suffixes of “banana” are:

\[S = \{ 'banana',\, 'anana',\, 'nana',\, 'ana',\, 'na',\, 'a',\, '' \}\]

Once we have inserted these seven words in a prefix tree, finding a fragment in the text is just a prefix search: The fragment occurs in the text if, and only if, there is at least one suffix that starts with it.

But where does it occur? We need to know where each suffix starts in the text. This is easy: A suffix that is \(k\) characters long, in a text of \(n\) characters, starts at position \(n - k\).

Let us look for “ana” in “banana”. Two suffixes start with “ana”: “anana” and “ana”. The text has 6 characters, so “anana” (5 characters) starts at position \(6 - 5 = 1\), and “ana” (3 characters) starts at position \(6 - 3 = 3\). We have found the two occurrences, at positions 1 and 3.

How Efficient Is This?

Once the tree is built, searching does not depend on how long the text is: We only walk down the tree, following the fragment, as we do in any prefix search. Our code is a bit wasteful, though. When we only want to know whether the fragment occurs, it still collects all the matching suffixes, whereas we could stop as soon as we have followed the whole fragment in the tree. That would take \(O(|f|)\) steps for a fragment \(f\).

Building the tree is the expensive part. A text of \(n\) characters has \(n + 1\) suffixes, which are, on average, \(n/2\) characters long, so the tree stores about \(n^2/2\) symbols, and takes about as long to build. This is fine for a short text, but hopeless for a book, or a genome with billions of characters.

Fortunately, there are better ways. We can compress the tree, as we did for prefix trees, and store positions in the text, instead of copying the suffixes. There are even clever algorithms that build such a compressed suffix tree in time proportional to \(n\) (Ukkonen’s algorithm is the best known). They are beyond the scope of this course, but the idea is the one we have just seen: A suffix tree is a prefix tree of all the suffixes.