Start learning free

LESSON 501 OF 671 · TRIES

Implement Trie (Prefix Tree) in Java with HashMap Nodes

Practice O(L) Read the full explanation

A trie (pronounced "try"), or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each of its children adds one more letter to that prefix. Words that begin the same way share the same path from the root, so a trie can tell whether a word was added, or whether any added word starts a certain way, in time that depends only on the length of the word asked about. Autocomplete and spell checkers work this way.

Implement the class Trie:

  • Trie() creates an empty trie.
  • insert(word) adds the string word to the trie.
  • search(word) returns true if word was inserted before, and false otherwise.
  • startsWith(prefix) returns true if some inserted word starts with prefix, and false otherwise. A word counts as a prefix of itself.

The input is a list of operations, applied in order to one new trie. The output lists what the search and startsWith calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
    insert("apple")
    search("apple")
    search("app")
    startsWith("app")
    insert("app")
    search("app")
Output: true false true true
Explanation:
"apple" was inserted, so search("apple") is true.
"app" is only the beginning of "apple": search("app") is false, but startsWith("app") is true.
After insert("app"), search("app") is true.

Example 2:

Input:
    insert("car")
    insert("cart")
    startsWith("ca")
    search("ca")
    startsWith("cat")
    search("cart")
Output: true false false true
Explanation: Both words start with "ca", but "ca" itself was never inserted. No word starts with "cat".

Example 3:

Input:
    insert("dog")
    insert("dog")
    search("dog")
    startsWith("dog")
    search("do")
    startsWith("dogs")
    search("dogs")
Output: true true false false false
Explanation: Inserting "dog" a second time changes nothing. "dog" is a prefix of itself, so startsWith("dog") is true. Nothing longer than "dog" was inserted.

 

Constraints:

  • 1 <= word.length, prefix.length <= 30
  • word and prefix consist of lowercase English letters, a to z.
  • At most 105 calls in total are made to insert, search and startsWith.

Note:

Each operation should run in O(L) time, where L is the length of its word or prefix.

STEP 1 OF 18
    Ctrl + Enter to check

    JAVA · TRIES

    Implement Trie Prefix Tree in Java, explained

    Problem overview

    A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each child adds one more letter to it. Words that start the same way share the same path from the root.

    The class Trie has three methods. insert(String word) adds a word. search(String word) returns true only if that exact word was inserted. startsWith(String prefix) returns true if some inserted word begins with prefix; a word counts as a prefix of itself. Each operation should take O(L) time, where L is the length of the word or prefix.

    After insert("apple"), search("apple") is true, but search("app") is false because "app" is only the beginning of a longer word, while startsWith("app") is true. After insert("app"), search("app") becomes true.

    Approach: one node per prefix, with an end flag

    Storing the words in a set would answer search quickly, but startsWith would have to check every word. A trie answers both by walking down from the root, one letter per level, so the cost depends only on the length of the query.

    Each node needs two things:

    • its children: a map from the next letter to the child node for that letter;
    • an end flag, isEnd, that is true when an inserted word finishes at this node.

    The flag is what separates "apple was inserted" from "apple's prefix exists". After inserting "apple", the nodes for "app" and "apple" both exist, but only the node for "apple" has isEnd set. The root stands for the empty prefix, and an empty trie is just a root with no children.

    All three operations share the same walk. insert creates missing nodes along the way and marks the last one. search walks without creating anything and returns the flag of the last node. startsWith walks the same way and returns true if it never fell off the trie.

    Step by step

    1. Give TrieNode a children field of type Map<Character, TrieNode>, initialised to a new HashMap. Map keys must be objects, so the key type is Character, the wrapper class of char. Java converts between them automatically. Because the field has an initial value, every new node gets its own empty map and the class needs no constructor.
    2. Add the flag: boolean isEnd = false.
    3. Give Trie a root field set to new TrieNode().
    4. In insert, start a variable node at root and loop over word.toCharArray().
    5. For each letter, if node.children has no key for it (containsKey), put a new TrieNode under that letter. Then move down with node = node.children.get(c). The child exists by now, whether it was already there or was just created.
    6. After the loop, set node.isEnd = true. This marks the word as inserted and not only as the start of a longer word.
    7. In search, do the same walk from root, but when a letter has no child, return false at once: nothing was inserted along that path. After the loop, return node.isEnd.
    8. In startsWith, repeat the walk with the same early false. If the loop completes, the whole prefix exists as a path, and every node in a trie lies on the path of some inserted word, so return true.

    The solution in Java

    class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isEnd = false;
    }
    
    class Trie {
        TrieNode root = new TrieNode();
    
        public void insert(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!node.children.containsKey(c)) {
                    node.children.put(c, new TrieNode());
                }
                node = node.children.get(c);
            }
            node.isEnd = true;
        }
    
        public boolean search(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!node.children.containsKey(c)) {
                    return false;
                }
                node = node.children.get(c);
            }
            return node.isEnd;
        }
    
        public boolean startsWith(String prefix) {
            TrieNode node = root;
            for (char c : prefix.toCharArray()) {
                if (!node.children.containsKey(c)) {
                    return false;
                }
                node = node.children.get(c);
            }
            return true;
        }
    }
    

    Java details worth understanding:

    • Autoboxing. containsKey(c), put(c, ...) and get(c) take an object, and the char c is boxed into a Character for each call. Passing an int such as 99 instead would box to an Integer, which is a different key type and would never match.
    • HashMap.get returns null for a missing key. The code tests containsKey first, so get is only called for a key that exists. Calling get and checking for null would also work, and does one lookup instead of two.
    • toCharArray() turns a String into a char[], which the for-each loop walks one letter at a time.
    • Imports. Map and HashMap are in java.util, so a file of your own needs import java.util.*;.
    • Package-private members. The fields have no modifier, so other classes in the same package can reach them. That is fine for a small exercise.

    Complexity

    Time: O(L) per operation. Each loop turn does one hash lookup, one possible insertion and one move down, and the loop runs once per letter. These map operations take constant time on average.

    Space: O(total letters) in the worst case, for the words inserted: a new node is created for each letter that isn't already on a path. Words that share prefixes share nodes, so the real cost is often lower.

    Edge cases and common mistakes

    • Prefix against word. After inserting "car" and "cart", startsWith("ca") is true and search("ca") is false, since no word ended at "ca".
    • Returning true from search after the walk. The path being present isn't enough. The method must return node.isEnd.
    • Inserting a word twice. After inserting "dog" twice, nothing changes: the nodes exist and isEnd is set again. search("dog") is true.
    • A word that is a prefix of itself. startsWith("dog") is true after inserting "dog".
    • Longer than anything inserted. startsWith("dogs") and search("dogs") are both false after inserting only "dog": the walk falls off at "s".
    • Creating nodes inside search. A query must not change the trie, or later queries will see words that were never inserted.

    Testing

    These results come from running the class:

    • Insert "apple", then search("apple"), search("app"), startsWith("app"): true, false, true. Insert "app", then search("app"): true.
    • Insert "car", "cart", then startsWith("ca"), search("ca"), startsWith("cat"), search("cart"): true, false, false, true.
    • Insert "dog" twice, then search("dog"), startsWith("dog"), search("do"), startsWith("dogs"), search("dogs"): true, true, false, false, false.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free