Implement Trie (Prefix Tree)

Medium

Topics
TrieDesignHash TableString

Implement a trie with insert(word), search(word) (returns whether the exact word was inserted), and startsWith(prefix) (returns whether any inserted word has the given prefix).

Example 1

returnsTrie()insert(apple)search(apple)truesearch(app)falsestartsWith(app)trueinsert(app)search(app)true
Each node holds one character and a map of children, so a shared prefix is stored once rather than per word. That is what makes startsWith cheap.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["Trie","insert","search","search","startsWith","insert","search"], values = [[],["apple"],["apple"],["app"],["app"],["app"],["app"]]
Output: [null,null,true,false,true,null,true]

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • Words consist of lowercase English letters.
  • At most 3*10^4 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A trie stores words along shared prefixes. Each node has up to 26 children and a flag marking the end of a complete word, so both exact search and prefix search walk the same path.

Approach

  1. Each node holds a children map and an isEnd flag.
  2. insert walks/creates nodes for each character, marking the last as end.
  3. search walks the path and checks isEnd; startsWith walks the path and only checks it exists.

Dry Run

insert "apple", then insert "app"
Each node is itself a Trie -- a map of child letters plus one boolean. After both
inserts:
  a
    p
      p (end)
        l
          e (end)
  insert apple     -> null
  search apple     -> true    walk a-p-p-l-e, end is set
  search app       -> false   the node exists, but its end flag is not set yet
  startsWith app   -> true    the node exists, and that is all startsWith asks
  insert app       -> null    sets end on the existing node; no new nodes created
  search app       -> true
answer null|null|true|false|true|null|true
Rows 3 and 4 are the entire reason this data structure exists. Both walk to the
same node; they disagree because search consults `end` and startsWith does not.
Drop the flag check from search and "app" reports true after only "apple" was
inserted -- which collapses the one distinction the trie is there to make.
The second insert adds no nodes at all. It walks the existing a-p-p path and only
flips a boolean, which is what makes a trie compact on a dictionary of words
sharing prefixes.
Nodes carry no character of their own. The letter lives on the EDGE, which is why
`ch` is a map keyed by character rather than a field on the node -- a node is
"whatever you reach by spelling this prefix".

Complexity

  • Time — O(L): each operation walks the word length L.
  • Space — O(total chars): nodes for every distinct prefix.

Common Pitfalls

  • search has to check end; startsWith must not. Dropping the flag check makes search("app") return true after only "apple" was inserted, which is the one distinction the data structure exists to make.
  • The node needs no character of its own. The edge into a node carries the letter, which is why ch is a map keyed by character rather than a field on the node.

Full Solution — all languages

class Trie:
    def __init__(self):
        self.ch = {}
        self.end = False
    def insert(self, word):
        node = self
        for c in word:
            node = node.ch.setdefault(c, Trie())
        node.end = True
    def _find(self, word):
        node = self
        for c in word:
            if c not in node.ch:
                return None
            node = node.ch[c]
        return node
    def search(self, word):
        n = self._find(word)
        return n is not None and n.end
    def startsWith(self, prefix):
        return self._find(prefix) is not None
SensAI
Beta
Tap the mic to stop voice mode