Sub topic 3
Inserting words
This chapter assumes you know Python dictionaries, basic classes, and Big-O notation. It also assumes you have read the previous chapter on the trie node, which has a children dictionary and an is_end flag.
What insertion does
Inserting a word means following the word's characters from the root. At each character, you reuse the child node if it exists. If it doesn't, you create it. After the last character, you mark that node as the end of a word.
Words that share a prefix share the nodes for that prefix. Inserting car and then card creates three nodes for car, then only one new node for d.
The code
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = TrueThe loop body does the main work. setdefault(ch, TrieNode()) returns the existing child for ch. If there is none, it stores a new TrieNode under ch and returns that. Either way, node moves one level down.
setdefault builds a new TrieNode on every call, even when the child already exists, and then throws it away. This is harmless for a tutorial. If you insert millions of words, you can avoid the waste with an explicit check:
child = node.children.get(ch)
if child is None:
child = TrieNode()
node.children[ch] = child
node = childA worked example
Insert car, card and cat in that order.
car: the root has no children, so the trie createsc,aandr. Thernode getsis_end = True.card:c,aandralready exist, so the trie only walks them. It createsdunderrand marksdas an end.cat:candaexist. The trie createstunderaand marks it as an end.
The result has five nodes below the root, not the ten that storing the three words separately would need.
Why the end marker matters
After step 1, the r node is an end. After step 2, it is still an end, because card only adds a child below it. The flag and the children are independent. A node can be an end and also have children.
If you left out is_end, the trie could not tell the stored word car from the mere prefix ca. Both are paths from the root.
Edge cases
| Input | Behavior |
|---|---|
| Duplicate word | The walk reuses every node and sets `is_end = True` again. Nothing changes. |
| Empty string `""` | The loop does not run, so the root becomes an end node. The trie now contains the empty word. |
| Word that is a prefix of an existing word | Only the flag changes. No new nodes are created. |
| Word that extends an existing word | New nodes are added below the old end node. |
Cost
Each character costs one dictionary lookup and, at most, one node creation. Both are O(1) on average. Insertion therefore takes O(L) time for a word of length L. It does not depend on how many words are already stored. The extra space is at most L new nodes, and often far fewer when prefixes are shared.
Common errors
- Forgetting
is_end = True. The nodes exist, butsearchcan never find the word. - Setting
is_endon every node along the path. Every prefix would then count as a word. - Resetting
nodeto the root inside the loop. Only the first character gets inserted. - Sharing one
TrieNodeobject between several parents, for example through a mutable default argument. This corrupts unrelated paths.
Exercise
You insert "to", then "tea", then "ten" into an empty trie. How many nodes exist below the root, and which nodes have is_end set to True?
Show answer
Five nodes: t, o, e, a and n. The "t" node is shared by all three words. The nodes with is_end = True are "o" (end of "to"), "a" (end of "tea") and "n" (end of "ten"). The "t" and "e" nodes are not ends.
Exercise
What happens to the trie if you call insert("car") twice, and why is it safe?
Show answer
Nothing changes the second time. Each character already has a child, so the walk reuses the existing nodes, and setting is_end = True on a node that is already True has no effect.