LeetCode 208: Implement Trie (Prefix Tree) — Python Solution

Solve LeetCode 208: Implement Trie (Prefix Tree) in Python with a nested child maps approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicTrie
Reusable patternnested child maps
ComplexityO(L) time per operation and O(total inserted characters) space

What the problem is testing

Each character follows or creates a child node, and a terminal flag distinguishes complete words from prefixes.

Algorithm

  1. Each character follows or creates a child node, and a terminal flag distinguishes complete words from prefixes.
  2. Maintain this invariant: The node reached after a prefix represents exactly that character sequence.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word):
        node = self.root
        for char in word: node = node.setdefault(char, {})
        node["$"] = True

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

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

    def _find(self, text):
        node = self.root
        for char in text:
            if char not in node: return None
            node = node[char]
        return node

Why this is correct

The proof follows the maintained state: The node reached after a prefix represents exactly that character sequence. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(L) time per operation and O(total inserted characters) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

An inserted word can also be a prefix of a longer word.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 127. Word Ladder · Next: 211. Design Add and Search Words Data Structure