Sub topic 8
Choosing how to store children
This chapter assumes you can write the TrieNode and Trie classes from earlier chapters, and that you know Big-O notation, dictionaries, and arrays. Each trie node needs a way to find the child that matches the next character. That choice affects memory use, speed, and the order in which you visit children.
The two common options
A node holds a collection of children, keyed by character. You can store it in one of two ways.
- Hash map (dictionary). Each node has a dictionary that holds only the children that exist. This is what the earlier chapters used.
- Fixed array. Each node has an array with one slot per symbol in the alphabet. For lowercase English letters that is 26 slots. The slot for
cis at indexord(c) - ord("a"), and an empty slot holdsNone.
class ArrayTrieNode:
def __init__(self):
self.children = [None] * 26
self.is_end = False
class ArrayTrie:
def __init__(self):
self.root = ArrayTrieNode()
@staticmethod
def _index(ch):
i = ord(ch) - ord("a")
if not 0 <= i < 26:
raise ValueError(f"unsupported character: {ch!r}")
return i
def insert(self, word):
node = self.root
for ch in word:
i = self._index(ch)
if node.children[i] is None:
node.children[i] = ArrayTrieNode()
node = node.children[i]
node.is_end = True
def search(self, word):
node = self.root
for ch in word:
node = node.children[self._index(ch)]
if node is None:
return False
return node.is_end
t = ArrayTrie()
t.insert("cat")
print(t.search("cat")) # True
print(t.search("ca")) # FalseThe helper _index rejects characters outside a to z. Without that check, an uppercase letter or a digit would give a negative or oversized index. A negative index would silently read the wrong slot in Python.
Comparing the two
Let L be the length of the key and A the alphabet size.
| Property | Hash map | Fixed array |
|---|---|---|
| Child lookup | O(1) on average | O(1) exactly |
| Memory per node | Proportional to the children present | `A` slots, even if empty |
| Alphabet | Any hashable symbol | Must be small and known in advance |
| Iterating children | Needs sorting for alphabetical order | Index order is already sorted |
| Search for a word | O(L) on average | O(L) |
Both options give O(L) search. The difference is in the constants and in memory.
The array is fast and predictable, and it avoids hashing. Its cost is space. A trie of 100,000 nodes with 26 slots each stores 2.6 million slots, and most of them are usually empty near the leaves. For Unicode text, with over a million code points, a full array per node is not practical.
The dictionary pays for hashing and per-entry overhead. It uses little memory when nodes have few children, which is the usual case. It also accepts any character without extra code.
Ordering and autocomplete
The autocomplete method from the earlier chapter calls sorted(node.children) at every node it visits. With an array, you loop over indices 0 to 25 and the order is alphabetical without sorting. With a dictionary, the sort costs O(k log k) per node, where k is the number of children. Since k is at most the alphabet size, this cost is small in practice. It still matters if you run autocomplete on every keystroke.
How to choose
- Use a dictionary by default. It handles any alphabet and wastes no space on empty slots.
- Use an array when the alphabet is small and fixed, such as lowercase letters or DNA bases (
A,C,G,T), and nodes are dense. - For very large alphabets, use a dictionary or a sorted list of
(character, child)pairs searched with binary search.
Exercise
A trie stores 50,000 words over the 26 lowercase letters and has 120,000 nodes. How many child slots does an array-based version allocate, and why might a dictionary-based version use less memory?
Show answer
The array version allocates 120,000 × 26 = 3,120,000 slots. Most of them are empty because the average node has only a few children (about one child per node, since 120,000 nodes have 119,999 parent-to-child links). A dictionary stores only the links that exist, so it holds roughly 120,000 entries plus per-dictionary overhead instead of 3.1 million slots.
Exercise
Why does an array-based trie return autocomplete results in alphabetical order without a sort step?
Show answer
The slot index comes from the character's position in the alphabet. Looping over indices 0 to 25 therefore visits children in alphabetical order, so a depth-first traversal produces words in sorted order.