Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in TypeScript: O(L) Operations

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

    TYPESCRIPT · TRIES

    Implement Trie Prefix Tree in TypeScript, explained

    Problem overview

    A trie, 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 it. Words that begin the same way share the same path from the root.

    The class Trie has three methods:

    • insert(word) adds a word;
    • search(word) returns true only if that exact 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, because "app" was never inserted as a word, while startsWith("app") is true. After insert("app"), search("app") becomes true.

    Approach

    Scanning a list of all inserted words for every question costs time that grows with the number of words. A trie makes each operation depend only on the length L of the word or prefix: follow its letters from the root, one level per letter.

    Two pieces of data make that work:

    • each TrieNode keeps children, an object that maps a letter to the child node for that letter, so the next step is found directly and only letters that some word uses take space;
    • each node also keeps a flag, isEnd, that is true where an inserted word ends. After inserting "apple" the nodes for "app" and "apple" both exist, and only the flag says which of them ends a word. That flag is the whole difference between search and startsWith.

    The root stands for the empty prefix, so an empty trie is a root with no children.

    Step by step

    1. The node's children. In TrieNode, children has the type Record<string, TrieNode>, an object whose keys are strings and whose values are TrieNodes, and starts as the empty object {}.
    2. The end flag. isEnd is a boolean that starts as false.
    3. The root. In Trie, root is a new TrieNode.
    4. insert: start at the root. A variable node begins at this.root and walks down as the letters are read.
    5. Loop over the letters. A for...of loop gives each character c of word.
    6. Create the path when it is missing. If c is not a key of node.children, store a new TrieNode under it. The test is !(c in node.children).
    7. Move down. node becomes node.children[c]. The child exists now, whether it was there before or was just created.
    8. Mark the end. After the loop, node is the node of the whole word, and node.isEnd becomes true.
    9. search: the same walk, creating nothing. If a letter has no child, return false: no inserted word goes this way.
    10. Return the flag. After the loop, return node.isEnd. Reaching the node is not enough, because the path for "app" exists after inserting "apple" although no word ends there.
    11. startsWith: the same walk again. A missing letter gives false.
    12. Return true. If every letter of the prefix had a child, its path exists, and every node of the trie lies on the path of some inserted word, so some word starts with it.

    The solution in TypeScript

    class TrieNode {
        children: Record<string, TrieNode> = {};
        isEnd: boolean = false;
    }
    class Trie {
        root: TrieNode = new TrieNode();
        insert(word: string): void {
            let node: TrieNode = 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: string): boolean {
            let node: TrieNode = this.root;
            for (const c of word) {
                if (!(c in node.children)) {
                    return false;
                }
                node = node.children[c];
            }
            return node.isEnd;
        }
        startsWith(prefix: string): boolean {
            let node: TrieNode = this.root;
            for (const c of prefix) {
                if (!(c in node.children)) {
                    return false;
                }
                node = node.children[c];
            }
            return true;
        }
    }
    

    Details for TypeScript:

    • Record<string, TrieNode> is only a type. When the code is compiled to JavaScript, children is just a plain object created by {}, and the type is erased.
    • The in operator tests whether a key exists in an object, so c in node.children is true when some inserted word continues with c at this node. It also sees properties an object inherits: "toString" in {} is true. For the single lowercase letters of this lesson no key like that exists, so the test is exact. If the keys could be longer words, a Map<string, TrieNode> would avoid the surprise.
    • Field initializers such as root: TrieNode = new TrieNode(); run for each new instance, so each Trie gets its own root and each TrieNode its own children object.
    • for (const c of word) iterates over the characters of a string, each one a one-character string, which suits the keys of children.

    Complexity

    Time: O(L) for each operation, where L is the length of the word or prefix: one loop turn per letter, and looking up a key in an object, creating a node and moving down are each constant work. Space: a trie holds at most one node per letter of each inserted word, so O(total letters) in the worst case; words with a shared beginning share nodes, which saves space.

    Edge cases and common mistakes

    • A word that is a prefix of another. After insert("car") and insert("cart"), search("car") is true and startsWith("ca") is true, but search("ca") is false.
    • Inserting the same word twice. The second insert("dog") finds the whole path and sets isEnd to true again: nothing changes.
    • A prefix of itself. After insert("dog"), startsWith("dog") is true, while startsWith("dogs") and search("do") are false.
    • Returning true from search at the end of the walk. It would make every prefix of an inserted word look like a word. The answer must be node.isEnd.
    • Creating nodes in search or startsWith. Those methods only read. Creating children there would make later startsWith calls succeed for prefixes of words that were never inserted.
    • Forgetting to mark the end. Without node.isEnd = true after the loop in insert, search could never return true.

    Testing

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