Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Python: Dict-Based Nodes

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

    PYTHON · TRIES

    Implement Trie Prefix Tree in Python, 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 that prefix. Words that begin the same way share the same path from the root, so a lookup takes time that depends only on the length of the word asked about, not on how many words are stored.

    The class Trie has three methods:

    • insert(word) adds word.
    • search(word) returns True only if word was inserted itself.
    • startsWith(prefix) returns True if some inserted word starts with prefix. A word counts as a prefix of itself.

    After insert("apple"), search("apple") is True, but search("app") is False: "app" is only the beginning of a longer word. startsWith("app") is True. After insert("app") as well, search("app") becomes True. Inserting the same word twice changes nothing.

    Approach: one node per prefix, one flag per word end

    The trie is made of TrieNode objects. Each node has a children dictionary that maps a letter to the child node for that letter, and a flag isEnd that says whether an inserted word finishes at this node. The trie keeps one root node, which stands for the empty prefix.

    The flag is needed because the path alone can't tell the difference between a word and the beginning of a longer one. After inserting "apple" and then "app", walking down the letters gives these nodes:

    a  isEnd=False  children=['p']
    p  isEnd=False  children=['p']
    p  isEnd=True   children=['l']
    l  isEnd=False  children=['e']
    e  isEnd=True   children=[]
    

    The third node, the one for "app", has isEnd=True only because "app" was inserted. Before that insert it was False, and the path was still there.

    All three methods are the same walk from the root, one letter at a time. They differ in what they do when a letter has no child and in what they return at the end:

    • insert creates the missing child and finally sets isEnd;
    • search returns False at a missing child, and at the end returns the node's isEnd;
    • startsWith returns False at a missing child, and at the end returns True, because every node of the trie lies on the path of some inserted word.

    Each operation visits one node per letter, so it takes O(L) time for a word of length L.

    Step by step

    1. Give TrieNode a children dict. In __init__, self.children = {} maps a letter to its child. A dictionary finds a child in one step and holds only the letters that some word uses.
    2. Add the isEnd flag, starting as False.
    3. Create the root. In Trie.__init__, set self.root to TrieNode(). An empty trie is a root with no children.
    4. In insert, start node at self.root.
    5. Loop over each character c of word. Each letter goes one level deeper.
    6. Create a missing child. If c is not in node.children, store a new TrieNode() under c.
    7. Move down with node = node.children[c]. The child exists now, whether it was there before or was just created.
    8. Mark the word's end. After the loop, set node.isEnd = True.
    9. In search, start at the root and loop over the letters of word in the same way, creating nothing.
    10. Return False at a missing letter. If c is not in node.children, nothing inserted continues this way.
    11. Move down to the child.
    12. Return node.isEnd after the loop. Reaching the node isn't enough, because the path may belong to a longer word only.
    13. In startsWith, repeat the walk over prefix, returning False at a missing letter.
    14. Return True after the loop. Every letter of the prefix had a child, so the path exists.

    The solution in Python

    class TrieNode:
        def __init__(self):
            self.children = {}
            self.isEnd = False
    
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()
    
        def insert(self, word: str) -> None:
            node = self.root
            for c in word:
                if c not in node.children:
                    node.children[c] = TrieNode()
                node = node.children[c]
            node.isEnd = True
    
        def search(self, word: str) -> bool:
            node = self.root
            for c in word:
                if c not in node.children:
                    return False
                node = node.children[c]
            return node.isEnd
    
        def startsWith(self, prefix: str) -> bool:
            node = self.root
            for c in prefix:
                if c not in node.children:
                    return False
                node = node.children[c]
            return True
    

    Python details worth a closer look:

    • Dictionary membership. c not in node.children checks the keys of the dict, in constant time on average. Reading node.children[c] for a missing key would raise KeyError, so every read comes after that check or after the insertion.
    • A fresh dict per node. self.children = {} runs in __init__, so every node gets its own dictionary. A dict written once in the class body would be shared by all nodes and mix every word together.
    • Iterating a string. for c in word gives one-character strings, which serve directly as dict keys.
    • The walk modifies a local name. node = node.children[c] only rebinds the variable node. self.root still points at the root afterwards.
    • Return types. search returns node.isEnd directly, which is already a bool.

    Complexity

    Time: O(L) per operation, where L is the length of the word or prefix. Each letter costs one dictionary lookup, plus one node creation in insert. With words of up to 30 letters, each call does at most 30 steps.

    Space: O(total letters inserted). At worst every inserted letter creates a new node. Words that share a prefix share its nodes, so the real count is often smaller. Searching and startsWith use no extra space.

    Edge cases and common mistakes

    • A prefix that was never inserted as a word. After inserting "car" and "cart", startsWith("ca") is True and search("ca") is False.
    • No word continues the letters. startsWith("cat") is False for the same two words, because the node for "ca" has only r as a child.
    • Inserting the same word twice. After inserting "dog" two times, search("dog") and startsWith("dog") are True, while search("do"), startsWith("dogs") and search("dogs") are False. The second insert finds every node already in place and sets the flag again.
    • A word longer than anything inserted. search("dogs") fails at the missing s child.
    • Forgetting isEnd in search. Returning True after the loop would make search("app") true after inserting only "apple".
    • Creating nodes while searching. A search or startsWith that adds missing children, such as with setdefault, makes later calls return wrong answers, because the trie then holds prefixes nobody inserted.
    • An empty trie. Before any insert, startsWith("a") and search("a") are both False, since the root has no children.

    Testing

    • Insert "apple", then search("apple"), search("app"), startsWith("app"), insert "app", search("app"): True, False, True, True.
    • Insert "car" and "cart", then startsWith("ca"), search("ca"), startsWith("cat"), search("cart"): True, False, False, True.
    • Insert "dog" twice, then search("dog"), startsWith("dog"), search("do"), startsWith("dogs"), search("dogs"): True, True, False, False, False.
    • On an empty trie, startsWith("a") and search("a"): False, False.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free