Skip to main content
36

Implement Trie (Prefix Tree)

Mediumtriedesign

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TriesRead the beginner guide

Implement a trie (also called a prefix tree, pronounced "try"): a structure that stores words so that looking up a word, or checking whether any word starts with some prefix, is fast.

Implement the class Trie:

  • new Trie() creates an empty trie.
  • insert(word) adds word.
  • search(word) returns true if word was inserted, otherwise false.
  • startsWith(prefix) returns true if some inserted word starts with prefix.

Understand the problem

  • A prefix is the beginning of a word: "app" is a prefix of "apple". Every word is also a prefix of itself.
  • search needs an exact word: after inserting only "apple", search("app") is false.
  • startsWith only needs some word to begin that way: startsWith("app") is true.
  • Think of autocomplete: as you type "app", it needs to quickly know which words start that way.

Example 1

text
ops:      ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
args:     [[],     ["apple"], ["apple"], ["app"], ["app"],       ["app"],  ["app"]]
expected: [null,   null,      true,      false,   true,          null,     true]
  • search("apple") → true: it was inserted.
  • search("app") → false: only "apple" was inserted so far.
  • startsWith("app") → true: "apple" starts with "app".
  • After insert("app"), search("app") → true.

How the tests work: each test is a sequence of calls. ops names each call (the first creates the object), args holds the arguments, and expected the return values (null for calls that return nothing).

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • Words and prefixes contain lowercase English letters only.
  • At most 3 * 10^4 calls in total.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Store words as paths in a tree where each step is one letter, and mark the nodes where a word ends; every operation is then a walk down the letters.

    The naive approach (and why it's slow)

    Keep all words in an array (or a set).

    • search(word): a set does this quickly. Fine.
    • startsWith(prefix): you have to check every stored word to see if it starts with the prefix. With 30,000 words, that's slow for each call.

    The key insight

    Words that start the same way can share their beginning. Store the letters as a tree, where each edge is a letter:

    Loading diagram...

    This trie holds car, card and care. Each node has:

    • children: a map from a letter to the next node.
    • isEnd: true if a word ends at this node (the nodes marked "end").

    Now every operation is just a walk down the letters, and its cost depends only on the length of the word, not on how many words are stored.

    OperationWalk the letters...Answer
    insert(word)creating any missing child along the waymark the last node isEnd
    search(word)if a letter is missing, stop: falsethe last node's isEnd
    startsWith(prefix)if a letter is missing, stop: falsetrue (reaching the end is enough)

    Step by step

    The calls from Example 1:

    CallWalkResult
    insert("apple")create a → p → p → l → e, mark e as end
    search("apple")walk to e, which is an endtrue
    search("app")walk to the second p, which is not an endfalse
    startsWith("app")walk to the second p: the path existstrue
    insert("app")the path exists; mark the second p as an end
    search("app")walk to the second p, now an endtrue

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With L = the length of the word or prefix:

    • Time: O(L) per call, no matter how many words are stored.
    • Memory: O(total letters inserted) in the worst case (when no beginnings are shared).

    Common mistakes

    • Forgetting isEnd. Without it, search("app") would wrongly return true after inserting only "apple".
    • Making search return true just because the path exists. That's startsWith. search also needs isEnd.
    • Storing the letter in the node instead of on the edge and getting confused about the root. The root is empty; the letters are the keys of children.

    Going deeper

    • With only lowercase letters, children can be an array of 26 slots instead of a map: slightly faster, more memory.
    • Tries power autocomplete, spell checkers and IP routing tables. You'll use one again in Design Add and Search Words and Word Search II.

    Reference solution

    js
    class TrieNode {
      children = new Map() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class Trie {
      root = new TrieNode() // the root holds no letter
    
      /**
       * @param {string} word
       * @return {void}
       */
      insert(word) {
        let node = this.root
        for (const char of word) {
          // Follow the letter, creating the node if this path doesn't exist yet.
          if (!node.children.has(char)) node.children.set(char, new TrieNode())
          node = node.children.get(char)
        }
        node.isEnd = true // mark that a word ends here
      }
    
      /**
       * @param {string} word
       * @return {boolean}
       */
      search(word) {
        // The path must exist AND a word must end exactly there.
        return this.#walk(word)?.isEnd ?? false
      }
    
      /**
       * @param {string} prefix
       * @return {boolean}
       */
      startsWith(prefix) {
        // Just reaching the end of the prefix is enough.
        return this.#walk(prefix) !== null
      }
    
      // Follow the letters from the root. Returns the last node, or null if a letter is missing.
      #walk(text) {
        let node = this.root
        for (const char of text) {
          node = node.children.get(char)
          if (!node) return null
        }
        return node
      }
    }
    ts
    class TrieNode {
      children = new Map<string, TrieNode>() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class Trie {
      private root = new TrieNode() // the root holds no letter
    
      insert(word: string): void {
        let node = this.root
        for (const char of word) {
          // Follow the letter, creating the node if this path doesn't exist yet.
          let child = node.children.get(char)
          if (!child) {
            child = new TrieNode()
            node.children.set(char, child)
          }
          node = child
        }
        node.isEnd = true // mark that a word ends here
      }
    
      search(word: string): boolean {
        // The path must exist AND a word must end exactly there.
        return this.walk(word)?.isEnd ?? false
      }
    
      startsWith(prefix: string): boolean {
        // Just reaching the end of the prefix is enough.
        return this.walk(prefix) !== null
      }
    
      // Follow the letters from the root. Returns the last node, or null if a letter is missing.
      private walk(text: string): TrieNode | null {
        let node: TrieNode | undefined = this.root
        for (const char of text) {
          node = node.children.get(char)
          if (!node) return null
        }
        return node
      }
    }
    python
    class TrieNode:
        def __init__(self):
            self.children: dict[str, TrieNode] = {}  # letter → next node
            self.is_end = False  # does a whole word end at this node?
    
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()  # the root holds no letter
    
        def insert(self, word: str) -> None:
            node = self.root
            for char in word:
                # Follow the letter, creating the node if this path doesn't exist yet.
                node = node.children.setdefault(char, TrieNode())
            node.is_end = True  # mark that a word ends here
    
        def search(self, word: str) -> bool:
            # The path must exist AND a word must end exactly there.
            node = self._walk(word)
            return node is not None and node.is_end
    
        def starts_with(self, prefix: str) -> bool:
            # Just reaching the end of the prefix is enough.
            return self._walk(prefix) is not None
    
        # Follow the letters from the root. Returns the last node, or None if a letter is missing.
        def _walk(self, text: str) -> TrieNode | None:
            node = self.root
            for char in text:
                node = node.children.get(char)
                if node is None:
                    return None
            return node