Bird
Raised Fist0
DSA Pythonprogramming~10 mins

Autocomplete System with Trie in DSA Python - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to insert a word into the Trie.

DSA Python
def insert(self, word):
    node = self.root
    for char in word:
        if char not in node.children:
            node.children[char] = [1]()
        node = node.children[char]
    node.is_end_of_word = True
Drag options to blanks, or click blank then click option'
ATrieNode
Bdict
Clist
Dset
Attempts:
3 left
💡 Hint
Common Mistakes
Using dict or list instead of TrieNode for children.
2fill in blank
medium

Complete the code to check if a prefix exists in the Trie.

DSA Python
def starts_with(self, prefix):
    node = self.root
    for char in prefix:
        if char not in node.children:
            return [1]
        node = node.children[char]
    return True
Drag options to blanks, or click blank then click option'
A0
BTrue
CNone
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning True or None when prefix is missing.
3fill in blank
hard

Fix the error in the search method to correctly find a word in the Trie.

DSA Python
def search(self, word):
    node = self.root
    for char in word:
        if char not in node.children:
            return False
        node = node.children[[1]]
    return node.is_end_of_word
Drag options to blanks, or click blank then click option'
Aword
Bchar
Cself
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word' or 'self' instead of 'char'.
4fill in blank
hard

Fill both blanks to collect all words starting with a prefix using DFS.

DSA Python
def dfs(self, node, prefix, results):
    if node.is_end_of_word:
        results.append(prefix)
    for [1], child_node in node.children.items():
        self.dfs(child_node, prefix + [2], results)
Drag options to blanks, or click blank then click option'
Achar
Bnode
Cprefix
Dchild_node
Attempts:
3 left
💡 Hint
Common Mistakes
Using node or child_node as the character key.
5fill in blank
hard

Fill all three blanks to implement the autocomplete method returning all words with given prefix.

DSA Python
def autocomplete(self, prefix):
    node = self.root
    for [1] in prefix:
        if [2] not in node.children:
            return []
        node = node.children[[3]]
    results = []
    self.dfs(node, prefix, results)
    return results
Drag options to blanks, or click blank then click option'
Achar
Bprefix
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prefix' as loop variable or key instead of 'char'.

Practice

(1/5)
1. What is the main purpose of using a Trie in an autocomplete system?
easy
A. To sort words alphabetically
B. To efficiently store and search prefixes of words
C. To count the total number of words
D. To encrypt the stored words

Solution

  1. Step 1: Understand the role of Trie in prefix search

    A Trie is a tree-like data structure designed to store strings by their prefixes, allowing quick prefix-based searches.
  2. Step 2: Connect Trie usage to autocomplete

    Autocomplete requires finding all words starting with a given prefix efficiently, which Trie supports by traversing nodes matching the prefix.
  3. Final Answer:

    To efficiently store and search prefixes of words -> Option B
  4. Quick Check:

    Trie = prefix search [OK]
Hint: Trie stores prefixes for fast autocomplete search [OK]
Common Mistakes:
  • Thinking Trie sorts words alphabetically
  • Confusing Trie with hash tables
  • Assuming Trie encrypts data
2. Which of the following is the correct way to insert a word "cat" into a Trie node in Python?
easy
A. node['c'] = TrieNode()
B. node.insert('c')
C. node.add('c')
D. node.children['c'] = TrieNode()

Solution

  1. Step 1: Understand Trie node structure

    Trie nodes typically have a dictionary called children to map characters to child nodes.
  2. Step 2: Insert character as a key in children dictionary

    To insert 'c', assign a new TrieNode to node.children['c'].
  3. Final Answer:

    node.children['c'] = TrieNode() -> Option D
  4. Quick Check:

    Insert char in children dict = node.children['c'] = TrieNode() [OK]
Hint: Use children dictionary to add new character nodes [OK]
Common Mistakes:
  • Trying to assign directly to node['c'] without children
  • Using non-existent methods like add or insert
  • Confusing list with dictionary for children
3. Given the following code snippet, what will be the output?
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end = True

    def search_prefix(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return False
            node = node.children[char]
        return True

trie = Trie()
trie.insert('dog')
trie.insert('deer')
print(trie.search_prefix('de'))
print(trie.search_prefix('do'))
print(trie.search_prefix('da'))
medium
A. True\nFalse\nFalse
B. False\nTrue\nFalse
C. True\nTrue\nFalse
D. False\nFalse\nFalse

Solution

  1. Step 1: Insert words 'dog' and 'deer' into Trie

    Both words add nodes for their characters. 'dog' adds d->o->g, 'deer' adds d->e->e->r.
  2. Step 2: Check prefixes 'de', 'do', and 'da'

    'de' exists as prefix in 'deer', so returns True. 'do' exists as prefix in 'dog', so True. 'da' does not exist, so False.
  3. Final Answer:

    True True False -> Option C
  4. Quick Check:

    Prefix 'de' and 'do' found, 'da' not found = True, True, False [OK]
Hint: Check prefix path existence in Trie children [OK]
Common Mistakes:
  • Confusing search_prefix with full word search
  • Assuming 'da' prefix exists
  • Ignoring is_end flag for prefix search
4. The following code is intended to insert words into a Trie, but it raises an error. What is the error?
class TrieNode:
    def __init__(self):
        self.children = []
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
medium
A. TypeError: list indices must be integers or slices, not str
B. AttributeError: 'TrieNode' object has no attribute 'children'
C. SyntaxError: invalid syntax
D. No error, code runs fine

Solution

  1. Step 1: Identify data structure used for children

    The code uses a list for children, but tries to access it with string keys.
  2. Step 2: Understand list indexing rules

    Lists require integer indices, but code uses node.children[char] where char is a string, causing TypeError.
  3. Final Answer:

    TypeError: list indices must be integers or slices, not str -> Option A
  4. Quick Check:

    Using list with string keys causes TypeError [OK]
Hint: Use dictionary, not list, for children to index by characters [OK]
Common Mistakes:
  • Using list instead of dict for children
  • Ignoring error message details
  • Assuming code runs without error
5. You want to implement an autocomplete system that returns all words starting with a given prefix using a Trie. Which approach correctly collects all matching words after reaching the prefix node?
hard
A. Perform a depth-first search (DFS) from the prefix node, collecting words where is_end is True
B. Return all children keys of the prefix node without further traversal
C. Only return the prefix itself without searching deeper
D. Use breadth-first search (BFS) but ignore is_end flags

Solution

  1. Step 1: Reach the node matching the prefix

    Traverse the Trie to the node representing the last character of the prefix.
  2. Step 2: Collect all words starting from prefix node using DFS

    Use DFS to explore all child nodes recursively, collecting words where is_end is True to get complete words.
  3. Final Answer:

    Perform a depth-first search (DFS) from the prefix node, collecting words where is_end is True -> Option A
  4. Quick Check:

    DFS from prefix node with is_end check = correct autocomplete [OK]
Hint: Use DFS from prefix node, collect words at is_end True [OK]
Common Mistakes:
  • Returning only immediate children keys
  • Ignoring is_end flags and returning incomplete words
  • Using BFS without checking word ends
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