Implement Trie (Prefix Tree)

Store words letter by letter in a tree, so that whole words and word beginnings can both be looked up.

Write a class that stores words and answers two kinds of questions about them. It has three methods:

Words and prefixes use only the lowercase letters a to z. In the examples, the output lists what search and startsWith return, in order, since insert returns nothing.

Example 1
Input: insert("apple"), search("apple"), search("app"), startsWith("app"), insert("app"), search("app")
Output: true, false, true, true
Example 2
Input, on the same object after Example 1: insert("apt"), startsWith("apt"), search("ap"), startsWith("b")
Output: true, false, false
Solution

The Idea

Type "ap" into a search box on your phone, and it can offer apple, app and apt as you type. All three words begin with the same two letters. The beginning of a word, like "app" in "apple", is called a prefix.

Example 1 shows why the two questions are different. After insert("apple"), the call search("app") returns false, because "app" was never added as a word. Yet startsWith("app") returns true, because "apple" begins with it. Once insert("app") runs, search("app") turns true.

So the object has to remember two things: which letter sequences begin some stored word, and where each whole word ends. How can it store the words so that both questions are answered by following the letters, without checking every word one by one?

Write each word as a path, one letter per step, all starting from the same place. Look at the picture below. It shows the words of both examples: apple, app and apt.

The trie after inserting apple, app and apt. From the root, links labelled a and p lead to the node ap. There it splits: p leads to app, a word end, then l and e lead to apple, also a word end. The link t leads to apt, a word end. The path a, p, p for search app is highlighted in orange.

Each box is a node, and the arrows between them are links, each labelled with one letter. Start at the box labelled root and follow the orange links: a, then p, then p. They lead to the box app. Going on along l and e reaches apple. At the box ap the path splits, because apt goes on with t where app goes on with p. The letters written inside a box are the ones spelled on the way to it.

The three words have 11 letters between them, yet the picture has only six boxes besides root. The words apple, app and apt share their first two links, and app is the start of apple. A tree of letter links like this, where every path from the root spells a prefix of some stored word, is called a trie, or prefix tree.

The teal boxes, marked "word end", are where an inserted word stops. That mark is what tells the two questions apart. The call startsWith("app") only needs the orange path to exist. The call search("app") also needs the box at its end to be teal. Before insert("app") ran, the box app was already there as part of apple, but it was not marked, so search("app") was false.

Solution Approach

Why build a trie at all, when a set of words is simpler? Once that is answered, three things need settling: what a node holds, how insert adds a path, and how the two questions follow one.

Keeping the words in a set

Why not keep the words in a HashSet? Then search is a single lookup. But a set only finds whole words, so startsWith("ap") would have to check every stored word for the prefix. With a million words, that is a million checks per call. In the trie, startsWith("ap") follows two links, however many words are stored.

What a node holds

What does one box of the picture need to know? Its links, and whether a word ends there. With only the letters a to z, the links fit in an array of 26 slots, named next. Slot 0 is for a, slot 1 for b, and so on, and a slot with no link holds null. The slot for a letter ch is ch - 'a', so p goes in slot 15 and t in slot 19. The box ap in the picture has exactly those two slots filled.

A boolean named isWord is the teal "word end" mark. The node does not store its own letters: the path that leads to it already spells them, so the labels inside the boxes are only there for reading the picture.

As an optional change, a HashMap from letter to node can replace the array. It works for any alphabet and saves memory when a node has few children, at the cost of hashing each letter.

Adding a path with insert

How does insert("apt") change the picture? It starts at root and follows the letters. The links a and p exist already, from apple, so it simply moves along them to the box ap. There is no t link at ap, so it creates a new node in slot 19 and moves into it. When the letters run out, it sets isWord on the node it stands on, the box apt. Inserting a word that is already stored creates nothing and sets a mark that is already set.

Answering search and startsWith

Both questions start with the same walk: from root, follow one link per letter. If a slot is null on the way, no stored word begins with these letters, and both answers are false. For example, the walk for startsWith("b") stops at root, which has no b link. If the walk uses up all the letters, startsWith answers true. The method search answers true only if isWord is set on the node where the walk ended.

Leaving out that last check is a real trap. A version of search that only asks whether the path exists, run with just "apple" inserted, returns true for search("app"), the opposite of Example 1.

Java Solution

The class has these parts:

  • The class Node is one box of the picture, with its 26 links in next and the word end mark in isWord.
  • The field root is the box labelled root, an empty node where every walk starts.
  • The method insert follows the letters from root, creates each missing node, and sets isWord on the last one.
  • The private helper walk follows the letters of a string from root and returns the node it reaches, or null when a link is missing.
  • The methods search and startsWith both call walk. Only search also checks isWord.

The main method runs Example 1 and then Example 2 on the same trie, and then asks about a word longer than any stored one and about the empty string.

Java
public class ImplementTrie {
    private static class Node {
        Node[] next = new Node[26]; // one slot per letter, 'a' to 'z'
        boolean isWord;             // true if an inserted word ends exactly here
    }

    private final Node root = new Node();

    public void insert(String word) {
        Node cur = root;
        for (char ch : word.toCharArray()) {
            int i = ch - 'a';
            if (cur.next[i] == null) cur.next[i] = new Node(); // create the path as needed
            cur = cur.next[i];
        }
        cur.isWord = true;
    }

    public boolean search(String word) {
        Node node = walk(word);
        return node != null && node.isWord; // the path exists and a word ends there
    }

    public boolean startsWith(String prefix) {
        return walk(prefix) != null; // the path exists
    }

    // Follows the letters of s from the root; null if the path breaks off.
    private Node walk(String s) {
        Node cur = root;
        for (char ch : s.toCharArray()) {
            cur = cur.next[ch - 'a'];
            if (cur == null) return null;
        }
        return cur;
    }

    public static void main(String[] args) {
        ImplementTrie trie = new ImplementTrie();
        // Example 1
        trie.insert("apple");
        System.out.println("search(\"apple\") -> " + trie.search("apple"));
        System.out.println("search(\"app\") -> " + trie.search("app"));
        System.out.println("startsWith(\"app\") -> " + trie.startsWith("app"));
        trie.insert("app");
        System.out.println("search(\"app\") -> " + trie.search("app"));
        // Example 2, on the same trie
        trie.insert("apt");
        System.out.println("startsWith(\"apt\") -> " + trie.startsWith("apt"));
        System.out.println("search(\"ap\") -> " + trie.search("ap"));
        System.out.println("startsWith(\"b\") -> " + trie.startsWith("b"));
        // Edge cases
        System.out.println("search(\"apples\") -> " + trie.search("apples"));
        System.out.println("startsWith(\"\") -> " + trie.startsWith(""));
        System.out.println("search(\"\") -> " + trie.search(""));
    }
}

Running it prints:

Output
search("apple") -> true
search("app") -> false
startsWith("app") -> true
search("app") -> true
startsWith("apt") -> true
search("ap") -> false
startsWith("b") -> false
search("apples") -> false
startsWith("") -> true
search("") -> false

Look at the two lines for search("app"): false while only apple is stored, then true once insert("app") has marked the box app. With apt added, search("ap") still prints false, since the box ap is on three paths but no word ends there, and startsWith("b") prints false because root has no b link.

Then comes search("apples") -> false: the walk reaches the box apple, finds no s link there and returns null. The last two lines are about the empty string. Here walk("") follows no links and returns root itself, so startsWith("") is true, since every word begins with nothing, and search("") is false, since root is never marked as a word end.

Complexity

Every call follows one link per letter, so its cost depends on the length of the word, not on how many words are stored.

  • Time: O(L) per call, where L is the length of the word or prefix, because insert and walk do one array lookup per letter, and insert creates at most one node per letter.
  • Space: O(T × 26), where T is the total number of letters inserted, because in the worst case no two words share a prefix and every letter gets its own node with a 26-slot array. Shared prefixes, like ap in the picture, use less.

Adding a wildcard letter to the search is Design Add and Search Words Data Structure.