Python Recursion Cheat Sheet
Python Tries Cheat Sheet
1. What is a Trie?
- A tree-like data structure used to store strings efficiently.
- Each node represents a character in a string.
- Commonly used for prefix matching, autocomplete, and spell-check.
2. Key Points:
- Root node is empty (no character).
- Each path from root to a node represents a prefix.
- End-of-word markers indicate complete words.
3. Basic Trie Node Structure:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
4. Trie Operations:
Insert:
def insert(root, word):
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
Search:
def search(root, word):
node = root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
StartsWith (Prefix Search):
def starts_with(root, prefix):
Python Recursion Cheat Sheet
node = root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
5. Complexity:
- Insert: O(m) where m = length of word.
- Search: O(m)
- Prefix search: O(m)
6. Applications:
- Autocomplete systems
- Spell checkers
- Dictionary word lookups
- IP routing (longest prefix match)
7. Tips:
- Use defaultdict for cleaner child node creation.
- Memory usage can be high; consider compressing with a radix tree for optimization.