Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in C++ with unordered_map 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

    C++ · TRIES

    Implement Trie Prefix Tree in C++, 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 begin the same way share the same path from the root, so asking about a word or a prefix takes time that depends only on its length.

    The class Trie has three operations:

    • insert(word) adds a word;
    • search(word) returns true only if exactly that word was inserted;
    • startsWith(prefix) returns true if some inserted word begins with prefix. A word counts as a prefix of itself.

    After insert("apple"), search("apple") is true but search("app") is false, while startsWith("app") is true. After insert("app"), search("app") becomes true. Inserting the same word twice changes nothing. Words and prefixes are 1 to 30 lowercase letters, and each operation should run in O(L) time for a word of length L.

    Approach: one node per prefix

    A set of words would answer search in one lookup, but startsWith would have to scan every word. A trie answers both by walking from the root, one letter per level.

    Each node has two things:

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

    The root stands for the empty prefix, so an empty trie is one root with no children. Inserting "apple" creates a chain of five nodes below the root, for a, ap, app, appl and apple, and marks the last one as an end. The node for app exists but is not marked, which is exactly why search("app") is false at that point. Inserting "app" later only sets that node's flag.

    The three operations are the same walk with different endings. Counting the nodes, root included, gives: 1 node when empty, 6 after "apple", still 6 after "app" (only a flag changes), and 7 after "apt", which shares a and ap and adds only apt.

    Step by step

    1. Define the node. TrieNode holds children, an unordered_map<char, TrieNode*> that starts empty, and bool isEnd = false.
    2. Create the root in Trie with TrieNode* root = new TrieNode();. The values in the map are pointers too: each child is made with new and stays alive for as long as the trie uses it.
    3. In insert, start at the root. A pointer node walks down the trie.
    4. Loop over the letters. A range-based for gives each char c of word.
    5. Create a missing child. node->children.count(c) is 1 if the key exists and 0 if not. When it is 0, store new TrieNode() under c.
    6. Move down to node->children[c]. The child exists by now, new or old.
    7. Mark the end. After the loop, node is the node of the whole word, and setting isEnd there is what makes the word count as inserted.
    8. In search, walk the same way without creating anything. If a letter has no child, return false.
    9. Return node->isEnd at the end. Reaching the node is not enough: the path for "app" exists after inserting "apple", but no word ends there.
    10. In startsWith, do the same walk and return false at a missing letter. If the loop finishes, return true: every node lies on the path of some inserted word, so a complete path means some word starts with the prefix. The flag doesn't matter.

    The solution in C++

    struct TrieNode {
        unordered_map<char, TrieNode*> children;
        bool isEnd = false;
    };
    
    class Trie {
    public:
        TrieNode* root = new TrieNode();
    
        void insert(string word) {
            TrieNode* node = root;
            for (char c : word) {
                if (!node->children.count(c)) {
                    node->children[c] = new TrieNode();
                }
                node = node->children[c];
            }
            node->isEnd = true;
        }
    
        bool search(string word) {
            TrieNode* node = root;
            for (char c : word) {
                if (!node->children.count(c)) {
                    return false;
                }
                node = node->children[c];
            }
            return node->isEnd;
        }
    
        bool startsWith(string prefix) {
            TrieNode* node = root;
            for (char c : prefix) {
                if (!node->children.count(c)) {
                    return false;
                }
                node = node->children[c];
            }
            return true;
        }
    };
    

    The C++ details worth a closer look:

    • Why count before []. children[c] on a missing key inserts a null pointer for it. In insert that would be harmless, because the code overwrites it, but in search and startsWith it would add junk entries, and the next step would dereference a null pointer. Testing with count first keeps lookups from changing the map. The lookups after the check are safe because the key exists.
    • Default member values. bool isEnd = false; and TrieNode* root = new TrieNode(); are initialised where they are declared, so no constructor is needed. The compiler's default constructor creates an empty trie, which is the state the statement calls "creates an empty trie".
    • Memory. Every new allocates a node that the code never deletes, so the memory lives until the program ends. That is fine for a program that builds one trie, but a long-running program would need a destructor that deletes the children recursively, or unique_ptr in the map.
    • Arrays of 26 instead of a map. TrieNode* next[26] indexed by c - 'a' is faster and uses a fixed amount of memory per node, at the price of 26 pointers in every node, even those with one child. The map pays only for the children that exist.
    • Passing strings by value. The methods take string by value, which copies up to 30 characters per call. It is cheap here. const string& avoids the copy.

    Complexity

    Let L be the length of the word or prefix.

    Time: O(L) per operation. Each operation visits one node per letter and does a constant amount of work at each: an average O(1) hash lookup in an unordered_map, and at most one allocation when inserting. The cost doesn't depend on how many words the trie already holds.

    Space: O(total letters inserted) in the worst case. Each inserted word adds at most one node per letter, and words that share a prefix share nodes. With at most 100,000 operations of up to 30 letters, that is at most 3,000,000 nodes.

    Edge cases and common mistakes

    • Empty trie. search("a") and startsWith("a") are both false: the root has no children, so the walk stops at the first letter.
    • A word that is a prefix of another. After inserting "car" and "cart", search("car") and search("cart") are both true, because the node for car and the node for cart both have isEnd set.
    • Prefix that is not a word. With "car" and "cart" inserted, startsWith("ca") is true and search("ca") is false.
    • A prefix longer than any word. After inserting "dog", startsWith("dogs") and search("dogs") are both false: the walk runs out of children at s.
    • Duplicate inserts. A second insert("dog") finds every node already there, and sets a flag that is already true.
    • Returning true from search at the end of the path. This confuses a word with a prefix of a longer word. The isEnd check is what separates the two.
    • Forgetting to set isEnd in insert. Then search would be false for every word, though startsWith would still work.
    • Returning node->isEnd from startsWith. That would make it behave like search, so startsWith("app") would be false after inserting only "apple".

    Testing

    • insert("apple"), then search("apple"), search("app") and startsWith("app") give true, false, true. After insert("app"), search("app") gives true.
    • insert("car"), insert("cart"), then startsWith("ca"), search("ca"), startsWith("cat") and search("cart") give true, false, false, true.
    • insert("dog") twice, then search("dog"), startsWith("dog"), search("do"), startsWith("dogs") and search("dogs") give true, true, false, false, false.
    • On an empty trie, search("a") and startsWith("a") give false and false.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free