Data Structures · Visualization
Trie: Delete
Trie
Deleting a word from a trie unmarks its 'end of word' flag, and then cleans up any nodes along its path that are no longer needed — that is, nodes that have no children and aren't the end of any other word. Time: O(L), where L is the word's length. Space: O(L) for the recursive call stack.
Big-O: Lookup O(word length), independent of the number of words.
Trie: Delete
TrieDeleting a word from a trie unmarks its 'end of word' flag, and then cleans up any nodes along its path that are no longer needed — that is, nodes that have no children and aren't the end of any other word. This cleanup is usually done recursively from the last character back toward the root, stopping as soon as a node is found that is still needed for another word.
How Delete Works
- Search down the trie following the word's characters, keeping track of the path taken.
- If the word isn't found, there's nothing to delete.
- If found, unmark the final node's 'end of word' flag.
- Walking back up the path, remove any node that has no children and is not itself the end of another word.
- Stop removing as soon as a node is still needed (has children or marks another word's end).
Delete Worked Example
Input: Delete 'cat' from a trie containing only 'cat'
- Follow path: c -> a -> t, found and marked end of word
- Unmark 't' as end of word
- 't' has no children and isn't an end of word anymore → remove it
- 'a' now has no children and isn't an end of word → remove it
- 'c' now has no children and isn't an end of word → remove it
Output: The trie becomes empty (just the root remains)
Press ▶ Run to watch it step by step.
def delete(root, word):
def rec(node, i):
if node is None:
return None
if i == len(word):
node.is_end = False
else:
ch = word[i]
node.children[ch] = rec(node.children.get(ch), i + 1)
# prune node if empty and not an end
if not node.is_end and not node.children:
return None
return node
return rec(root, 0)
# example: delete "cat"Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Delete Time & Space Complexity
When to Use Delete
- Removing an outdated word from a dictionary or spell-check list
- Removing a discontinued product name from a search index
- Keeping an autocomplete index up to date as data changes
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.