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

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. 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

  1. Start at the root.
  2. For each character in the word, check if a child edge for that character already exists.
  3. If it exists, move to that child; if not, create a new child node and move to it.
  4. After placing the last character, mark that node as 'end of word'.

Insert Worked Example

Input: Insert 'dog' into a trie already containing 'do'

  1. root -> d (exists) -> o (exists, marked end-of-word for 'do')
  2. From 'o', check for child 'g': does not exist, create it
  3. root -> d -> o -> g (mark 'g' as end of word)

Output: The trie now recognizes both 'do' and 'dog'

Try your own input
Trie: Introduction
A tree where each path from the root spells out a word one character per edge — words sharing a prefix share the same starting path.
root
root
c
a
t
r
t
d
o
g
n
e
Active path End of word
Trie: Introduction
Press ▶ Run to watch it step by step.
Python · Tries in Code
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: insert
Input: Insert 'dog' into a trie already containing 'do'

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.

Insert Time & Space Complexity

TimeO(L), where L is the word's length
SpaceO(L) new nodes in the worst case

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.