Bird
Raised Fist0
DSA Pythonprogramming~30 mins

Trie Insert Operation in DSA Python - Build from Scratch

Choose your learning style10 modes available
Trie Insert Operation
📖 Scenario: Imagine you are building a simple phone directory app that stores names. To quickly find names starting with certain letters, you decide to use a Trie data structure.
🎯 Goal: You will build a Trie and insert words into it step-by-step. At the end, you will print the Trie structure to see how words are stored.
📋 What You'll Learn
Create a Trie node class with a dictionary for children and a boolean to mark end of word
Create a Trie class with an insert method to add words
Insert given words into the Trie
Print the Trie children dictionary of the root node after insertions
💡 Why This Matters
🌍 Real World
Tries are used in autocomplete features, spell checkers, and IP routing to quickly find words or prefixes.
💼 Career
Understanding Tries helps in roles involving search engines, text processing, and efficient data retrieval.
Progress0 / 4 steps
1
Create the TrieNode class
Create a class called TrieNode with an __init__ method that initializes two attributes: children as an empty dictionary and is_end_of_word as False.
DSA Python
Hint

Think of children as branches from this node to next letters, and is_end_of_word as a flag to mark if a word ends here.

2
Create the Trie class with root node
Create a class called Trie with an __init__ method that initializes an attribute root as a new TrieNode object.
DSA Python
Hint

The Trie has a root node from where all words start.

3
Add insert method to Trie
Inside the Trie class, add a method called insert that takes a parameter word. Use a variable node starting at self.root. For each character in word, if the character is not in node.children, add a new TrieNode for it. Move node to the child node for that character. After the loop, set node.is_end_of_word to True.
DSA Python
Hint

Think of walking down the branches for each letter, creating new branches if needed, and marking the end of the word.

4
Insert words and print root children
Create a Trie object called trie. Insert the words "cat", "car", and "dog" into trie using the insert method. Then print the keys of trie.root.children as a list.
DSA Python
Hint

The root children keys show the first letters of inserted words.

Practice

(1/5)
1. What is the main purpose of the insert operation in a Trie data structure?
easy
A. To delete a word from the Trie
B. To add a new word character by character into the Trie
C. To search for a word in the Trie
D. To count the total words stored in the Trie

Solution

  1. Step 1: Understand the insert operation

    The insert operation adds each character of a word into the Trie one by one, creating nodes if they don't exist.
  2. Step 2: Compare with other operations

    Deleting removes words, searching checks presence, counting totals words. Insert specifically adds words.
  3. Final Answer:

    To add a new word character by character into the Trie -> Option B
  4. Quick Check:

    Insert = Add word stepwise [OK]
Hint: Insert means adding word letters step-by-step [OK]
Common Mistakes:
  • Confusing insert with search or delete
  • Thinking insert counts words
  • Assuming insert removes words
2. Which of the following is the correct way to start inserting a word "cat" into an empty Trie in Python?
easy
A. for char in "cat": current = current.children[char] if char in current.children else current.children[char] = TrieNode()
B. for char in "cat": current = current.children[char]
C. for char in "cat": current.children[char] = TrieNode(); current = current.children[char]
D. for char in "cat": if char not in current.children: current.children[char] = TrieNode(); current = current.children[char]

Solution

  1. Step 1: Check condition before adding node

    We must check if the character node exists before creating a new one to avoid overwriting.
  2. Step 2: Move current pointer correctly

    After ensuring the node exists, move current to that child node for next character insertion.
  3. Final Answer:

    for char in "cat": if char not in current.children: current.children[char] = TrieNode(); current = current.children[char] -> Option D
  4. Quick Check:

    Check existence then add and move [OK]
Hint: Check if node exists before adding new one [OK]
Common Mistakes:
  • Not checking if child node exists before assignment
  • Not moving current pointer after insertion
  • Overwriting existing nodes
3. Consider the following code snippet for inserting the word "dog" into a Trie. What will be the printed output after insertion?
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

root = TrieNode()

word = "dog"
current = root
for char in word:
    if char not in current.children:
        current.children[char] = TrieNode()
    current = current.children[char]
current.is_end = True

print(list(root.children.keys()))
medium
A. ['d']
B. ['o']
C. ['g']
D. []

Solution

  1. Step 1: Insert characters one by one

    The first character 'd' is added as a child of root, so root.children has key 'd'.
  2. Step 2: Check what is printed

    Printing root.children.keys() shows the first level keys, which is ['d'] after insertion.
  3. Final Answer:

    ['d'] -> Option A
  4. Quick Check:

    Root children keys after insert = ['d'] [OK]
Hint: Root children keys show first inserted letters [OK]
Common Mistakes:
  • Expecting all letters at root level
  • Printing keys of last node instead of root
  • Confusing keys with values
4. The following code attempts to insert the word "bat" into a Trie but has a bug. What is the error?
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

root = TrieNode()
word = "bat"
current = root
for char in word:
    current.children[char] = TrieNode()
current = current.children[char]
current.is_end = True
medium
A. The children dictionary is not initialized
B. The is_end flag is set before inserting all characters
C. The current pointer is moved outside the loop, causing nodes to not be chained properly
D. The loop variable 'char' is not defined

Solution

  1. Step 1: Analyze loop and pointer movement

    The line moving current pointer is outside the loop, so current only moves after loop ends, not per character.
  2. Step 2: Understand effect on insertion

    Nodes for each character are created directly under root (no chaining), and only the last node's is_end is set.
  3. Final Answer:

    The current pointer is moved outside the loop, causing nodes to not be chained properly -> Option C
  4. Quick Check:

    Pointer must move inside loop to build chain [OK]
Hint: Move current pointer inside loop to link nodes [OK]
Common Mistakes:
  • Moving pointer outside loop
  • Not creating nodes conditionally
  • Setting is_end too early
5. You want to insert multiple words ["apple", "app", "ape"] into a Trie. After insertion, which of the following statements is TRUE about the Trie structure?
hard
A. The node for 'l' after "app" exists only for "apple"
B. The node for 'p' after 'ap' will have is_end = True for both "app" and "ape"
C. Each word creates a completely separate branch from root
D. The root node's is_end flag will be True after insertion

Solution

  1. Step 1: Understand shared prefixes in Trie

    Words "apple", "app", and "ape" share prefix "ap"; nodes for 'a' and 'p' are shared.
  2. Step 2: Check is_end flags for words

    "app" ends at second 'p' node, so that node's is_end = True; "apple" continues to 'l' and 'e', so 'l' node is not end, but 'e' node is end.
  3. Step 3: Analyze options

    The node for 'p' after 'ap' will have is_end = True for both "app" and "ape" is wrong because 'p' node cannot be end for both "app" and "ape"; 'ape' ends at 'e' node. Each word creates a completely separate branch from root is wrong because branches share prefix nodes. The root node's is_end flag will be True after insertion is wrong because root node is not end of any word.
  4. Final Answer:

    The node for 'l' after "app" exists only for "apple" -> Option A
  5. Quick Check:

    Shared prefix nodes, is_end marks word ends [OK]
Hint: Shared prefixes share nodes; is_end marks word ends only [OK]
Common Mistakes:
  • Assuming each word has separate root branch
  • Marking is_end on wrong nodes
  • Setting root is_end True incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard