Skip to content

Implement Trie (Prefix Tree)

Build a prefix tree that inserts words and answers whole-word and prefix lookups in O(length) time.

MediumTries
Solve on LeetCode

The problem

Design a class Trie for lowercase words. insert(word) adds a word, search(word) returns true if that exact word was inserted, and startsWith(prefix) returns true if any inserted word begins with prefix. Each call should take time proportional to the length of its argument.

Input Trie(), insert("chai"), search("cha"), startsWith("cha"), insert("chat"), search("chat"), startsWith("chi")

Output [null, null, false, true, null, true, false]

cha is only a prefix of chai, so search says false but startsWith says true.

Input Trie(), insert("dal"), search("dal"), search("da"), startsWith("dal"), insert("da"), search("da")

Output [null, null, true, false, true, null, true]

A whole word counts as a prefix of itself, and da becomes a word only once it is inserted.

Key constraint: Words can be 2,000 letters long and there can be 30,000 calls, so scanning every stored word on each call is too slow.

How to spot the pattern

  • You need many lookups by prefix, not just by exact word.
  • Words share beginnings, and you want to store each shared beginning only once.

The idea

A trie is a tree where each edge is a letter, so a word is a path from the root, and words with the same beginning share their first nodes. Inserting or looking up a word walks one node per letter, creating missing nodes when inserting. Each node also has a flag saying whether a word ends there, and that flag is the only difference between search (the path must exist and end on a flagged node) and startsWith (the path only has to exist).

Brute force: Keep a list of words and scan it on every call, which costs O(number of words * L) per lookup.

Step by step

  1. 1Give each node a map (or an array of 26) from letter to child, plus an isWord flag.
  2. 2insert: walk from the root letter by letter, create any missing child, and set isWord on the last node.
  3. 3Write one helper that follows a string from the root and returns the node it ends on, or null if a letter is missing.
  4. 4search: the helper's node must exist and have isWord set.
  5. 5startsWith: the helper's node only has to exist.

Code

class TrieNode:
    def __init__(self):
        self.children = {}  # letter -> TrieNode
        self.is_word = False  # True when a word ends at this node


class Trie:

    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_word = True

    def search(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and node.is_word

    def startsWith(self, prefix: str) -> bool:
        return self._walk(prefix) is not None

    def _walk(self, text: str) -> Optional[TrieNode]:
        # Follow text letter by letter; None means the path breaks off.
        node = self.root
        for ch in text:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

Complexity

Time

O(L)

Space

O(total letters)

Every call walks at most L nodes for a word or prefix of length L. The trie has at most one node per inserted letter, and fewer when words share prefixes.

Watch out for

  • Returning true from search just because the path exists: cha was not inserted just because chai was.
  • Forgetting to mark the end of a word, so search never succeeds.
  • Storing every prefix of every word in a hash set instead: it works, but costs O(L^2) memory per word.

Follow-up questions

Should the children be an array of 26 or a hash map?

An array is fast and simple for lowercase letters but wastes space in sparse nodes. A map stores only the letters that occur, which suits large alphabets.

How would you delete a word?

Walk to its last node and clear isWord. On the way back up, remove nodes that have no children and no word ending at them.

In Hinglish

Trie mein har letter ek kadam hai, aur ek jaisi shuruaat wale words ek hi raasta share karte hain. search ke liye aakhri node par isWord true chahiye, startsWith ke liye bas raasta hona kaafi hai.

Related problems