Data Structure Description
A trie is a data structure that stores words in a tree structure, with an empty root node and every subsequent node containing a character that together with its parents forms part or all of a word. Each trie node contains a value indicating whether the node is a terminal character in a word.
There are multiple ways to implement tries, but two main ones are to use nested dictionaries or Node objects.
Performance Characteristics
Let $n$ equal the number of words in the trie, $c_w$ equal the number of characters in a word $w$, and $c$ equal the number of characters in the longest word.
- Insert $w$: $\Theta(c_w)$
- Check for $w$: $\Theta(c_w)$
- Insert all words: $O(\sum c_w) = O(n \cdot c)$
- Check all words: $O(\sum c_w) = O(n \cdot c)$
Python Tree Implementation
class Node:
def __init__(self, val, children=None, terminal=False):
self.val = val
self.children = [] if children is None else children
self.terminal = terminal
class Trie:
def __init__(self, words: list[str]):
self.root = Node("")
for word in words:
self.insert(word)
def insert(self, word: str) -> None:
curr = self.root
for c in word:
for n in curr.children:
if n.val == c:
curr = n
break
else:
new_node = Node(c)
curr.children.append(new_node)
curr = new_node
curr.terminal = True
def contains(self, word: str) -> bool:
curr = self.root
for c in word:
for n in curr.children:
if n.val == c:
curr = n
break
else:
return False
return curr.terminal
Python Dictionary Implementation
TERMINAL = "TERMINAL"
class TrieDict:
def __init__(self, words: list[str]):
self.root = dict()
for word in words:
self.insert(word)
def insert(self, word: str) -> None:
curr = self.root
for c in word:
if c in curr:
curr = curr[c]
else:
curr[c] = dict()
curr = curr[c]
curr[TERMINAL] = True
def contains(self, word: str) -> bool:
curr = self.root
for c in word:
if c in curr:
curr = curr[c]
else:
return False
return TERMINAL in curr
Puzzles
| Puzzle | Difficulty | External Link |
| Suffix Pairs | Medium |

