π§© Python DSA Patterns β Trie (Prefix Tree) π²π
Posted on: January 16, 2026
Description:
A Trie (pronounced try) is a tree-like data structure used to store and search strings efficiently, especially when dealing with prefixes.
Instead of storing whole words, a Trie stores characters node by node, sharing common prefixes.
This makes Tries ideal for autocomplete, dictionary search, and prefix matching problems.
β¨ When to Use
- When you need fast prefix lookups.
- When searching words from a large dictionary.
- When checking if a word or prefix exists repeatedly.
- When multiple strings share common prefixes.
β‘ Why Trie is Efficient
- Search complexity depends on word length, not number of words.
- Shared prefixes reduce redundant storage.
- Prefix queries are extremely fast.
Time complexity:
- Insert β O(L)
- Search β O(L)
-
Prefix search β O(L)
(where L = length of the word)
π§© Trie Structure
Each Trie node contains:
- A dictionary of children (character β next node)
- A flag to indicate end of word
π Example 1 β Basic Trie Node & Insert
Build the structure and insert words character by character.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
π Example 2 β Search for a Word
Traverse character by character and check end-of-word.
def search(self, word):
node = self.root
for ch in word:
if ch not in node.children:
return False
node = node.children[ch]
return node.is_end
π Example 3 β Prefix Search (Starts With)
Check whether any word starts with the given prefix.
def starts_with(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return True
π§ Where It Helps
- π€ Autocomplete & search suggestions
- π Spell checkers & dictionaries
- π Prefix-based search (e.g., βall words starting with βpreββ)
- π§© Word search problems
- ποΈ Storing large vocabularies efficiently
β οΈ Limitations
- Higher memory usage than hash sets
- Not ideal for very short or random strings
- Requires careful memory management for large alphabets
β Takeaways
- Tries are optimized for string & prefix problems
- Operations run in O(length of word)
- Perfect for autocomplete & dictionary-based tasks
- One of the most elegant string data structures in DSA
ποΈ Practice Problems
- Implement Trie (Insert, Search, Prefix)
- Word Search II
- Design Add and Search Words Data Structure
- Replace Words
- Longest Word in Dictionary
No comments yet. Be the first to comment!