0% found this document useful (0 votes)
2 views2 pages

Python Tries Cheatsheet

A Trie is a tree-like data structure used for efficient string storage, commonly applied in prefix matching and autocomplete features. Key operations include insertion, searching, and prefix searching, all with a time complexity of O(m), where m is the length of the word. Applications of Tries include autocomplete systems, spell checkers, and dictionary lookups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Python Tries Cheatsheet

A Trie is a tree-like data structure used for efficient string storage, commonly applied in prefix matching and autocomplete features. Key operations include insertion, searching, and prefix searching, all with a time complexity of O(m), where m is the length of the word. Applications of Tries include autocomplete systems, spell checkers, and dictionary lookups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

You might also like