Data Structures · Visualization
Trie: Introduction
Trie
A trie (pronounced 'try', from reTRIEval) is a tree built specifically for storing strings, where each edge represents a single character and each path from the root spells out a prefix. Time: O(L) for insert/search/prefix-check, where L is the word's length. Space: O(total characters stored across all words).
Big-O: Lookup O(word length), independent of the number of words.
Trie: Introduction
TrieA trie (pronounced 'try', from reTRIEval) is a tree built specifically for storing strings, where each edge represents a single character and each path from the root spells out a prefix. Words that share a common beginning share the same path in the tree, which makes tries extremely efficient for prefix-based lookups like autocomplete. Each node also has a flag marking whether a complete word ends there.
How Trie: Introduction Works
- Start with a root node representing an empty string.
- For each word, walk down the tree one character at a time, following (or creating) a child node for each character.
- Mark the final node of a word as 'end of word'.
- Words sharing a prefix automatically share the same path from the root.
Trie: Introduction Worked Example
Input: Insert 'cat' and 'car' into an empty trie
- root -> c -> a -> t (mark 't' as end of word)
- Insert 'car': root -> c -> a already exist, reuse them
- root -> c -> a -> r (new branch, mark 'r' as end of word)
Output: root - c - a - t (end) \ r (end)
Press ▶ Run to watch it step by step.
class TrieNode:
def __init__(self):
self.children = {} # char -> node
self.is_end = False
# Each node is a map of children plus an
# end-of-word flag. Prefixes are SHARED.
# example: introTrie: Introduction Time & Space Complexity
When to Use Trie: Introduction
- Autocomplete and search-as-you-type suggestions
- Spell checkers
- IP routing tables (longest prefix matching)
- Word games like Boggle or Scrabble helpers
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.