Trie Flashcards
(5 cards)
What is a Trie?
A tree structure for storing strings with shared prefixes.
Use Case: Autocomplete, prefix search.
What are the key steps to implement a Trie?
- Create TrieNode with children dict.
- Insert: Add chars to nodes, mark end.
- Search: Traverse chars, check end.
Action: Explain steps for Implement Trie aloud.
How does a Trie apply to Implement Trie?
Build trie for insert/search using node dict to store chars and track word ends.
Example: Implement Trie.
What are the complexity and gotchas of a Trie?
Time complexity: O(m) for insert/search, Space complexity: O(m * n).
Gotchas include empty strings and case sensitivity.
Action: List edge cases for Implement Trie aloud.
Code example of a Trie.
```python
from typing import Dict
class TrieNode:
def __init__(self) -> None:
self.children: Dict[str, ‘TrieNode’] = {}
self.is_end: bool = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
~~~