A trie shares character edges among words with common prefixes. Following a path proves prefix existence; a separate terminal marker proves a complete stored word. Insertions may create edges, while queries should only follow existing ones.
Recognize it when Repeated queries depend on prefixes or incremental character choices.
Checking your account…
Trie Code Labs
Mental Model
A trie stores one character per edge and shares nodes among words with the same prefix. Following
the characters of a query reaches exactly its prefix node, if those edges exist.
Characters Label Edges
Represent each node as a dictionary from next character to child node. Insertion and lookup take
O(L) expected time for a length-L string, independent of how many other words share the path. The
dictionary contract(opens in a new tab)
supplies expected constant-time edge lookup. Memory depends on stored characters and alphabet
branching; sparse dictionaries avoid allocating a full alphabet array at every node.
Distinguish Prefix from Complete Word
Existing edges prove only that a prefix occurs. A terminal marker records that a stored word ends at
this node, distinguishing app from the prefix of apple. The empty word, if allowed, marks the
root terminal.
Separate Words from Prefixes
Reference
def trie_membership(words, queries):
root = {}
for word in words:
node = root
for character in word:
node = node.setdefault(character, {})
node[None] = True
result = []
for query in queries:
node = root
for character in query:
if character not in node:
node = None
break
node = node[character]
result.append([node is not None and None in node, node is not None])
return result
Practice
Implement trie_membership(words, queries). Return [is_word, is_prefix] for every query using explicit terminal markers.
Public tests
Verify word and prefix distinction
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Separate Words from Prefixes
def trie_membership(words, queries):
root = {}
for word in words:
node = root
for character in word:
node = node.setdefault(character, {})
node[None] = True
result = []
for query in queries:
node = root
for character in query:
if character not in node:
node = None
break
node = node[character]
result.append([node is not None and None in node, node is not None])
return result
Trace Prefix Paths and Terminal Membership Separately
Call the existing membership Lab with the empty word and ‘at’. The root itself is terminal for the empty query. The path for ‘a’ exists but is not terminal; only the next edge reaches the stored word ‘at’.
print(trie_membership(['', 'at'], ['', 'a', 'at', 'ax'])) followed by print(trie_membership([], ['']))
Step
Executed statement
State
Why
1
node[None] = True
empty word: root contains terminal key None
The empty word ends at the root without a character edge.
Prefix and complete-word answers are intentionally separate. In this Lab, an empty query is a prefix even if no stored word exists because its path is the root; its is_word flag still depends on whether the empty word was inserted.
Measure Shared Prefixes
For autocomplete or pruning, follow edges until the first missing character. The number traversed is
the longest stored prefix path; it does not imply a complete-word match.
Measure Trie Prefix Paths
Reference
def trie_prefix_match_lengths(words, queries):
root = {}
for word in words:
node = root
for character in word:
node = node.setdefault(character, {})
lengths = []
for query in queries:
node = root
matched = 0
for character in query:
if character not in node:
break
node = node[character]
matched += 1
lengths.append(matched)
return lengths
Practice
Implement trie_prefix_match_lengths(words, queries). Return the number of query characters whose edges exist from the root.
Public tests
Verify partial shared prefixes
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Measure Trie Prefix Paths
def trie_prefix_match_lengths(words, queries):
root = {}
for word in words:
node = root
for character in word:
node = node.setdefault(character, {})
lengths = []
for query in queries:
node = root
matched = 0
for character in query:
if character not in node:
break
node = node[character]
matched += 1
lengths.append(matched)
return lengths
Choose Trie or Hash Set
Use a hash set for whole-word membership and a trie when prefixes, incremental character search, or
dictionary-pruned backtracking dominate. Sorting strings can group prefixes compactly for offline
work, while a trie supports repeated online queries.
Prefix and Terminal Marker Mistakes
Omitting the terminal marker makes every prefix look like a word.
Creating child dictionaries during a read mutates the trie unexpectedly.
Copying prefix strings at every DFS node can add quadratic work.
A fixed alphabet array wastes space when the character domain is large or sparse.
Explain It in an Interview
Define what a node and terminal marker mean, then charge work to query characters. State the alphabet
assumption and why prefix existence differs from word existence.
Interview bounds depend on the stated representation, input model, and real Python operations.
Operation
Average
Worst
Interview note
Insert or query length L text
O(L + 1)
O((L + 1) * A)
A maximum child-map width; ordinary hashing gives expected constant edge operations. Insertion may allocate L nodes; lookup uses constant cursor space.
Build and return q query results
O(W + w + Q + q)
O((W + w + Q + q) * max(1, A))
W total stored word characters, w number of words, Q total query characters and q number of queries; empty words still incur one loop iteration, and the root always exists. Dictionary overhead and alphabet branching affect constants.
Space
O(L + 1) for insert or query length l text; O(W + q + 1) for build and return q query results.
Assumptions
A maximum child-map width; ordinary hashing gives expected constant edge operations. Insertion may allocate L nodes; lookup uses constant cursor space.
W total stored word characters, w number of words, Q total query characters and q number of queries; empty words still incur one loop iteration, and the root always exists. Dictionary overhead and alphabet branching affect constants.
Invariants Worth Saying Aloud
After k characters, node represents exactly that query prefix.
None terminal membership is separate from character-edge existence.
A lookup stops at the first absent edge and does not add new child mappings.
When To Use Or Avoid Trie
Use It When
Use a trie for online prefix lookup or dictionary-constrained search.
Keep a terminal marker when complete-word membership differs from prefix membership.
Choose Another Tool When
Use a hash set when only whole-word membership matters.
Do not allocate a full alphabet array at every node for a large sparse character domain.
Common Pitfalls
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
01
Accepting any existing prefix as a whole word
The path to 'a' can exist only because 'at' was inserted. A terminal marker is needed to distinguish complete words.
Prevent it: Test terminal membership after completing the query path.