Trie
A prefix tree that stores strings letter by letter along its branches. By sharing common prefixes, it handles autocomplete, dictionaries, and prefix search in O(m) where m is the string length.
01Trie
Explore How It WorksStart a trie. Store strings letter by letter along the branches, and shared prefixes share the same path.
insert('cat') · build a new path c → a → t from the root, marking the final t as a 'word end'.
insert('car') · c·a already exist and are shared, so only r is added — sharing the prefix is the key idea.
insert('dog') · the very first letter differs, so build a completely new branch d → o → g.
search('car') · follow the letters c → a → r from the root, and since r is a 'word end', it's found.
Sharing common prefixes saves memory, and a lookup finishes in O(m), the word length. This is the basis of autocomplete.
02 Understand It Simply
For EveryoneCharacters form the edges, so words sharing a prefix share a path. Lookup time depends on the word's length, not on the size of the dictionary.
A tree that stores strings letter by letter, sharing common prefixes.
It finds a word in O(m) and quickly gathers all words starting with a given prefix.
- –Search autocomplete
- –dictionaries and spell-check
- –IP routing
03 Python Implementation
A clean, readable reference implementation of the core logic of Trie.
04 Frequently Asked Questions
FAQWhat is Trie?+
A prefix tree that stores strings letter by letter along its branches. By sharing common prefixes, it handles autocomplete, dictionaries, and prefix search in O(m) where m is the string length.
What is the time complexity of Trie?+
The time complexity of Trie is O(m) (string length). Follow the step-by-step visualization to see exactly why.
Where is Trie used?+
Search autocomplete, dictionaries and spell-check, IP routing.
What's a simple analogy for Trie?+
Characters form the edges, so words sharing a prefix share a path. Lookup time depends on the word's length, not on the size of the dictionary.
