Topic 11 of 14

Trie Patterns

1 pattern and 5 practice problems, each with a recall tip, a diagram, the theory and a Python template.

01

Trie - Prefix Matching

5 practice problems

Theory

  • Each node has a dictionary of children and an is_end flag.
  • Insert: walk the tree, create nodes as needed, mark end.
  • Search: walk the tree, return is_end at the final node.
  • Prefix search: like search but return True if final node exists (don't check is_end).

Code template

python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

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

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_end = True

    def search(self, word):
        node = self._find(word)
        return node is not None and node.is_end

    def starts_with(self, prefix):
        return self._find(prefix) is not None

    def _find(self, s):
        node = self.root
        for ch in s:
            if ch not in node.children:
                return None
            node = node.children[ch]
        return node

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.