Data Structures · Visualization
Trie: Insert
Trie
Inserting a word walks down the trie one character at a time from the root: for each character, follow the existing child if there is one, or create a brand-new child node if not. Time: O(L), where L is the word's length. Space: O(L) new nodes in the worst case.
Big-O: Lookup O(word length), independent of the number of words.
Trie: Insert
TrieInserting a word walks down the trie one character at a time from the root: for each character, follow the existing child if there is one, or create a brand-new child node if not. Once every character of the word has been placed, the final node is flagged to mark that a complete word ends there.
How Insert Works
- Start at the root.
- For each character in the word, check if a child edge for that character already exists.
- If it exists, move to that child; if not, create a new child node and move to it.
- After placing the last character, mark that node as 'end of word'.
Insert Worked Example
Input: Insert 'dog' into a trie already containing 'do'
- root -> d (exists) -> o (exists, marked end-of-word for 'do')
- From 'o', check for child 'g': does not exist, create it
- root -> d -> o -> g (mark 'g' as end of word)
Output: The trie now recognizes both 'do' and 'dog'
Press ▶ Run to watch it step by step.
def insert(root, word):
cur = root
for ch in word:
if ch not in cur.children:
cur.children[ch] = TrieNode()
cur = cur.children[ch]
cur.is_end = True
# O(word length)
# example: insertBehind 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.
Insert Time & Space Complexity
When to Use Insert
- Building a dictionary of valid words for a spell checker
- Loading a set of product names for search suggestions
- Adding new terms to an autocomplete index
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.