Loading
Loading
A tree keyed by character, so shared prefixes are stored once.
Each edge carries a character and each path from the root spells a prefix. Lookup costs time proportional to the length of the word rather than the number of words stored, and every prefix query becomes a simple walk down from the root.
The structure pays for itself when prefixes are shared. Its real advantage in search problems is early termination: the moment a path is not a prefix of any word, the entire branch can be abandoned.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
class TrieNode: def __init__(self): self.children = {} # A node can be both the end of one word and an interior node of a # longer one, so this flag is not the same as "is a leaf". self.is_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_word = True def search(self, word): node = self._walk(word) return node is not None and node.is_word def starts_with(self, prefix): return self._walk(prefix) is not None def _walk(self, text): node = self.root for char in text: if char not in node.children: return None node = node.children[char] return node| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Shared Label Prefix#142 | Easy | Primary | |
| Prefix Tally#143 | Medium | Primary | |
| Root Shorthand#144 | Medium | Primary |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in