Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Implementation in Python

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Trie runs in O(m) time and O(n*m) space, in Python as in every other language.
  • ✓The standard library ships no trie. You build one from dict: either a node class with __slots__ = ('children', 'is_word') holding dict[str, TrieNode], or the classic nested plain dict with a sentinel key such as a module-level _END = object().
  • ✓Reviewers want __slots__ on the node so a million nodes do not each carry a __dict__, and they want the descent loop written with children.get(ch) rather than try/except KeyError in the hot path.
  • ✓The Python trap: The defaultdict trie is a read-mutating trie. Because defaultdict.__getitem__ inserts the default on a miss, calling search('cats') on a trie that only has 'cat' silently creates the 's' node and every node under the miss path, so a read-only query grows the structure and later prefix enumeration reports phantom branches.
  • ✓The big-O hides an interpreter constant: each edge step is a bytecode-level dict lookup plus an attribute load, roughly 40-80 ns on a current CPython (measured 43 ns for children.get(ch) plus the attribute load on 3.14), so a 20-char word costs about a microsecond, not nanoseconds.

What Trie actually is

A trie (prefix tree) stores string keys as paths of single-symbol edges: the key lives in the walk from the root, not in any one node, and every node marks whether a key ends there. Lookup, insert and delete are O(m) in the key length with no hashing of the whole key and no collisions. Engineers reach for it when the query is prefix-shaped rather than exact: autocomplete and typeahead, longest-prefix-match routing tables, dictionary/word-break checks, IP and URL prefix rules, and streaming multi-pattern search (Aho-Corasick is a trie plus failure links). A hash map beats it for pure exact lookup; the trie wins the moment you need 'all keys starting with X' or ordered traversal.

Trie in Python: what you actually reach for

The standard library ships no trie. You build one from dict: either a node class with __slots__ = ('children', 'is_word') holding dict[str, TrieNode], or the classic nested plain dict with a sentinel key such as a module-level _END = object(). collections.defaultdict supports the one-liner Trie = lambda: defaultdict(Trie). For production, the ecosystem answers are pygtrie (pure Python, CharTrie/StringTrie/PrefixSet, dict-like API) and marisa-trie (a C++ MARISA binding, static and immutable but an order of magnitude smaller in RAM). functools/bisect give you nothing here.

Python implementation

Reviewers want __slots__ on the node so a million nodes do not each carry a __dict__, and they want the descent loop written with children.get(ch) rather than try/except KeyError in the hot path. Iterating the key directly (for ch in word) is expected; indexing word[i] in a range loop gets flagged. Prefix enumeration is expected to be a generator yielding keys, not a list built in memory, and deletion is expected to be iterative with a parent stack.
python
from collections import deque

class TrieNode:
    __slots__ = ("children", "is_word")

    def __init__(self) -> None:
        self.children: dict[str, "TrieNode"] = {}
        self.is_word = False

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

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

    def _walk(self, prefix: str) -> "TrieNode | None":
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)   # .get, never [], or you mutate on read
            if node is None:
                return None
        return node

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

    def with_prefix(self, prefix: str):
        start = self._walk(prefix)
        if start is None:
            return
        stack = deque([(start, prefix)])   # explicit stack: no recursion limit
        while stack:
            node, acc = stack.pop()
            if node.is_word:
                yield acc
            for ch, child in node.children.items():
                stack.append((child, acc + ch))

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

The defaultdict trie is a read-mutating trie. Because defaultdict.__getitem__ inserts the default on a miss, calling search('cats') on a trie that only has 'cat' silently creates the 's' node and every node under the miss path, so a read-only query grows the structure and later prefix enumeration reports phantom branches. Use .get() for every lookup path and reserve __getitem__ for insert. Second Python-specific trap: a recursive delete or DFS blows the 1000-frame default recursion limit on long keys such as URLs or DNA strings. On CPython 3.10 and older, raising sys.setrecursionlimit traded that RecursionError for a genuine C-stack segfault; since 3.11 inlined Python-to-Python calls and 3.12 gave C recursion its own separate limit, a raised limit on a pure-Python DFS is survivable (200k frames measured fine on 3.14). Keep an explicit list as the stack anyway: it is version-independent, and any C-level frame in the recursion still puts the crash back.

Performance in Python, beyond the O(m)

The big-O hides an interpreter constant: each edge step is a bytecode-level dict lookup plus an attribute load, roughly 40-80 ns on a current CPython (measured 43 ns for children.get(ch) plus the attribute load on 3.14), so a 20-char word costs about a microsecond, not nanoseconds. Memory dominates: an empty dict is 64 bytes plus the node object header, so a naive char-per-node trie over 100k words easily exceeds 100 MB. __slots__ removes 48+ bytes per node; collapsing single-child chains into a radix edge removes most nodes outright. marisa-trie exists precisely because CPython object overhead, not the algorithm, is the cost. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie between languages.

Real-World Applications

Trie applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Trie?

The standard library ships no trie. You build one from dict: either a node class with __slots__ = ('children', 'is_word') holding dict[str, TrieNode], or the classic nested plain dict with a sentinel key such as a module-level _END = object(). collections.defaultdict supports the one-liner Trie = lambda: defaultdict(Trie). For production, the ecosystem answers are pygtrie (pure Python, CharTrie/StringTrie/PrefixSet, dict-like API) and marisa-trie (a C++ MARISA binding, static and immutable but an order of magnitude smaller in RAM). functools/bisect give you nothing here.

What is the most common Python mistake when implementing Trie?

The defaultdict trie is a read-mutating trie. Because defaultdict.__getitem__ inserts the default on a miss, calling search('cats') on a trie that only has 'cat' silently creates the 's' node and every node under the miss path, so a read-only query grows the structure and later prefix enumeration reports phantom branches. Use .get() for every lookup path and reserve __getitem__ for insert. Second Python-specific trap: a recursive delete or DFS blows the 1000-frame default recursion limit on long keys such as URLs or DNA strings. On CPython 3.10 and older, raising sys.setrecursionlimit traded that RecursionError for a genuine C-stack segfault; since 3.11 inlined Python-to-Python calls and 3.12 gave C recursion its own separate limit, a raised limit on a pure-Python DFS is survivable (200k frames measured fine on 3.14). Keep an explicit list as the stack anyway: it is version-independent, and any C-level frame in the recursion still puts the crash back.

How does Trie actually perform in Python?

The big-O hides an interpreter constant: each edge step is a bytecode-level dict lookup plus an attribute load, roughly 40-80 ns on a current CPython (measured 43 ns for children.get(ch) plus the attribute load on 3.14), so a 20-char word costs about a microsecond, not nanoseconds. Memory dominates: an empty dict is 64 bytes plus the node object header, so a naive char-per-node trie over 100k words easily exceeds 100 MB. __slots__ removes 48+ bytes per node; collapsing single-child chains into a radix edge removes most nodes outright. marisa-trie exists precisely because CPython object overhead, not the algorithm, is the cost. Time complexity is O(m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.