The ultimate structure for string search and autocomplete. Store words character by character for blazing fast prefix lookups in O(L) time.
A Trie is a tree where each node represents a single character. Paths down the tree form words.
is_word flag.is_word = True.is_word at the end.Time Complexity: O(L) for insert/search, where L is the length of the word.
class TrieNode: def __init__(self): self.children = {} # char -> TrieNode self.is_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: curr = self.root for char in word: if char not in curr.children: curr.children[char] = TrieNode() curr = curr.children[char] curr.is_word = True def search(self, word: str) -> bool: curr = self.root for char in word: if char not in curr.children: return False curr = curr.children[char] return curr.is_word def startsWith(self, prefix: str) -> bool: curr = self.root for char in prefix: if char not in curr.children: return False curr = curr.children[char] return True