Python Snippet

Trie Implementation in Python

Difficulty: Medium

A trie (prefix tree) stores strings character-by-character so prefix queries run in O(length) instead of O(N * length). The Pythonic shape uses a dict of dicts plus a sentinel key for 'word ends here'. This entry covers the dict-of-dicts trie, a class-based variant with explicit nodes, and the autocomplete query you build it for.

Code Snippets
/

Trie Implementation in Python

Trie Implementation in Python

A trie (prefix tree) stores strings character-by-character so prefix queries run in O(length) instead of O(N * length). The Pythonic shape uses a dict of dicts plus a sentinel key for 'word ends here'. This entry covers the dict-of-dicts trie, a class-based variant with explicit nodes, and the autocomplete query you build it for.

Python
Medium
3 snippets
trie
trie-operations
data-structures
py-standard-library

697 views

21

The dict-of-dicts shape is the simplest trie that works: every node is a dict, keys are next characters, values are child dicts. A sentinel key ('__end__' here) marks 'a word ends at this node', which is what distinguishes a stored word from a mere prefix. setdefault is the one-liner for 'get or create the next node'. Insertion and lookup are both O(length) and the storage cost is one dict entry per character of input. This is the right starting trie for autocomplete prototypes, spell checkers, and the LeetCode 'Implement Trie' family.