Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in JavaScript: O(L) Insert and Search

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

    JAVASCRIPT · TRIES

    Implement Trie Prefix Tree in JavaScript, 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.

    The task is to implement a class Trie with three methods:

    • insert(word) adds a word.
    • search(word) returns true only if that exact word was inserted before.
    • 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, search("app") is false, and startsWith("app") is true. After insert("app") too, search("app") becomes true. Inserting the same word twice changes nothing. Each operation should run in O(L) time, where L is the length of the word or prefix.

    Approach: a node per prefix, a flag per word

    Storing the words in an array and scanning it would make every question cost time proportional to the number of words. A trie makes it depend only on the length of the word asked about: to follow a word, you step down one level per letter.

    Each TrieNode holds two things:

    • children, an object that maps a letter to the child node for that letter. It only holds the letters that some word actually continues with.
    • isEnd, a flag that is true when an inserted word ends at this node.

    The flag is needed because the nodes can't tell the difference by themselves. After inserting "apple", the nodes for "app" and "apple" both exist, but only the second one ends a word.

    After inserting "car", "cart" and "cat", the root has one child, c. That node has one child, a, which has two children, r and t. The r node has isEnd set to true and also a child t, so "car" is a word and a prefix of "cart". The node for "ca" has isEnd set to false.

    The three operations differ only in what they do while walking down and what they return at the end:

    • insert creates any missing node on the way, then sets isEnd on the last one.
    • search fails if a node is missing, and otherwise returns the last node's isEnd.
    • startsWith fails if a node is missing, and otherwise returns true.

    Step by step

    1. Give TrieNode an empty object for children. It works as a map from a letter to a node and finds the child for a letter in one step.
    2. Set isEnd to false. It becomes true where an inserted word ends.
    3. Create the root in the Trie constructor. It stands for the empty prefix, so an empty trie is a root with no children.
    4. In insert, start node at the root. The walk always begins there.
    5. Loop over the letters of word with for...of. Each letter goes one level down.
    6. Create a missing child. If c is not a key of node.children, store a new TrieNode under it.
    7. Move down to node.children[c], which exists now whether it was already there or was just created.
    8. Mark the end. After the loop, node is the node of the whole word, and isEnd = true makes the word count as inserted.
    9. In search, start at the root and follow the letters, creating nothing.
    10. Loop over the letters of word.
    11. Return false when a letter has no child, since no inserted word continues that way.
    12. Move down to the child.
    13. Return node.isEnd. Reaching the node isn't enough, because the path for "app" exists after inserting "apple" while no word ends there.
    14. In startsWith, start at the root and do the same walk over prefix.
    15. Loop over the letters of prefix.
    16. Return false on a missing child: no word starts with this prefix.
    17. Move down to the child.
    18. Return true. Every node of the trie lies on the path of some inserted word, so if the whole prefix could be followed, a word starting with it exists.

    The solution in JavaScript

    class TrieNode {
        constructor() {
            this.children = {};
            this.isEnd = false;
        }
    }
    
    class Trie {
        constructor() {
            this.root = new TrieNode();
        }
    
        insert(word) {
            let node = this.root;
            for (const c of word) {
                if (!(c in node.children)) {
                    node.children[c] = new TrieNode();
                }
                node = node.children[c];
            }
            node.isEnd = true;
        }
    
        search(word) {
            let node = this.root;
            for (const c of word) {
                if (!(c in node.children)) {
                    return false;
                }
                node = node.children[c];
            }
            return node.isEnd;
        }
    
        startsWith(prefix) {
            let node = this.root;
            for (const c of prefix) {
                if (!(c in node.children)) {
                    return false;
                }
                node = node.children[c];
            }
            return true;
        }
    }
    

    The JavaScript details worth a closer look:

    • An object as a map. {} with letters as keys works as a dictionary here. Reading a missing key gives undefined, so the code checks for the key first and never reads a child that isn't there.
    • in tests for a key. "a" in node.children is true when the key exists, even if its value were undefined. The !( ) around it negates the whole test. Writing !c in node.children would negate c first and give the wrong test.
    • Inherited names. in also sees properties an object inherits, so "constructor" in {} is true. That can't affect this code: the keys tested are single lowercase letters, and no inherited property has a one-letter name. A Map would avoid the question altogether.
    • for...of over a string gives one character at a time, as a one-character string.
    • Shared walking code. search and startsWith repeat the same loop. That is fine for this lesson, and a helper that returns the final node (or null) would remove the repetition.
    • node is a moving reference. Reassigning node only moves the pointer. The nodes stay in the trie, linked from their parents' children.

    Complexity

    Time: O(L) per operation. Each operation does one step per letter of its argument, and every step is a key test and a lookup in an object, plus at most one node creation. The number of words stored doesn't matter.

    Space: O(N) in total, where N is the number of letters in the inserted words, in the worst case where no two words share a prefix. Shared prefixes are stored once. search and startsWith use O(1) extra space, and insert adds at most L nodes.

    Edge cases and common mistakes

    • A word that is a prefix of another. After inserting "car" and "cart", search("car") and search("cart") are both true, because isEnd is set on two different nodes.
    • A prefix that isn't a word. With "car" and "cart" inserted, startsWith("ca") is true and search("ca") is false.
    • Nothing longer inserted. After inserting "dog", startsWith("dogs") and search("dogs") are false, and search("do") is false.
    • Inserting a word twice. The second walk finds every node already there and sets isEnd to true again. Nothing changes.
    • Returning true from search without checking isEnd. That turns search into startsWith.
    • Forgetting to set isEnd in insert. Then no word is ever found by search.
    • Creating nodes while searching. search and startsWith must only read. If they created missing children, later calls would answer wrongly for prefixes nobody inserted.
    • An empty string. The tests only use words and prefixes of at least one letter. If you try it yourself, startsWith("") returns true and search("") returns false unless the root's isEnd is set.

    Testing

    Results of the search and startsWith calls, in order:

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