Sub topic 5
Cost of operations: O(L) in the key length
This chapter assumes you know Big-O notation, dictionaries, and the trie node and insert/search code from the earlier chapters. It explains why trie operations cost O(L), where L is the length of the key, and where that claim stops being true.
The working model
Every trie operation walks one path from the root. Each step handles one character and does one child lookup. With a dictionary, that lookup is O(1) on average. So a path of L characters costs O(L).
The number of stored words, n, does not appear in this walk. The trie never compares your key against other keys. It only follows edges that match the key's own characters.
Seeing it run
This script counts the nodes visited while following a key. It runs the same lookup against a trie with one word and a trie with 10,001 words.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
def build(words):
root = TrieNode()
for word in words:
node = root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = True
return root
def lookup_steps(root, key):
node = root
steps = 0
for ch in key:
node = node.children.get(ch)
if node is None:
break
steps += 1
return steps
small = build(["banana"])
large = build(["banana"] + [f"x{i}" for i in range(10000)])
print(lookup_steps(small, "banana")) # 6
print(lookup_steps(large, "banana")) # 6Both calls take 6 steps. The larger trie holds 10,000 more words, and that adds nothing to the lookup.
Cost of each operation
| Operation | Time | Why |
|---|---|---|
| Insert | O(L) | Walk or create one node per character. |
| Exact search | O(L) | Follow L edges, then check `is_end`. |
| Prefix check | O(P) | Follow P edges, where P is the prefix length. |
| Delete | O(L) | Walk down, then unwind the recursion. |
| Autocomplete | O(P + S) | Walk to the prefix node, then visit the S nodes in its subtree. |
A failed search can finish early. Searching for "cxyz" stops at the second character if no child "x" exists under "c". The worst case is still O(L).
Autocomplete depends on the size of the answer's subtree, not only on the prefix. With a limit, the traversal stops once enough words are found. Sorting children at each node adds a factor for the alphabet size k, so each node costs about O(k log k).
Comparing with other structures
| Structure | Exact search | Prefix query |
|---|---|---|
| Trie | O(L) | O(P + S) |
| Hash set | O(L) average | O(n · L) by scanning every word |
| Sorted array | O(L log n) | O(P log n + S) with binary search |
A hash set also pays O(L), because hashing a string reads every character. A trie is not faster for exact lookup. Its advantage is that it answers prefix questions directly.
Common errors in cost reasoning
- Writing O(n) for lookup. n is the number of words. Lookup cost depends on L. A trie of a million words and a trie of ten words answer a 6-letter query in the same number of steps.
- Ignoring the child lookup. O(L) assumes O(1) per child lookup. A hash map gives that on average. A fixed array of size k gives it exactly. If you stored children in an unsorted list, each step would cost O(k), and the total would be O(L · k).
- Forgetting that L can be large. O(L) is cheap for words but not for long strings such as URLs or DNA sequences. Compare it against the other structures using L, not n.
- Confusing time with space. Insertion creates at most L new nodes, so total space is O(total characters stored) in the worst case. Shared prefixes reduce it. The cost per node is high, which a later chapter covers.
Exercise
A trie holds 50,000 words. You search for a 5-letter word that is not stored, and its first letter matches no child of the root. How many child lookups happen, and what is the worst-case bound for this operation?
Show answer
One child lookup happens, because the search stops at the first missing edge. The worst-case bound is still O(L), here O(5), and it does not depend on the 50,000 stored words.
Exercise
Why is autocomplete O(P + S) instead of O(P)?
Show answer
Finding the prefix node takes O(P) steps. Collecting the words then visits every node in that node's subtree, S nodes, unless a limit stops it early. The result size is part of the work.