Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Autocomplete System with Trie in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Autocomplete Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Trie Insertion and Search
What is the output of the following code that inserts words into a Trie and searches for a prefix?
DSA Python
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 starts_with(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()
words = ["dog", "deer", "deal"]
for w in words:
    trie.insert(w)

print(trie.starts_with("de"))
print(trie.starts_with("da"))
ATrue\nTrue
BFalse\nTrue
CFalse\nFalse
DTrue\nFalse
Attempts:
2 left
💡 Hint
Check if the prefix exists in the Trie nodes after insertion.
🧠 Conceptual
intermediate
1:30remaining
Understanding Trie Node Structure
Which of the following best describes the structure of a Trie node used in an autocomplete system?
AA node contains a pointer to the next node and a count of words passing through it.
BA node contains a dictionary of children nodes and a boolean indicating if it is the end of a word.
CA node contains only a list of words that start with the prefix up to that node.
DA node contains a single character and a pointer to the parent node.
Attempts:
2 left
💡 Hint
Think about how to efficiently check prefixes and word endings.
🔧 Debug
advanced
2:30remaining
Identify the Bug in Autocomplete Suggestion Code
What error will the following code produce when trying to get autocomplete suggestions for prefix 'ca'?
DSA Python
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 _dfs(self, node, prefix, results):
        if node.is_end:
            results.append(prefix)
        for char in node.children:
            self._dfs(node.children[char], prefix + char, results)

    def autocomplete(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return []
            node = node.children[char]
        results = []
        self._dfs(node, prefix, results)
        return results

trie = Trie()
words = ["cat", "car", "cart", "dog"]
for w in words:
    trie.insert(w)

print(trie.autocomplete("ca"))
ATypeError: 'int' object is not iterable
BAttributeError: 'NoneType' object has no attribute 'children'
CNo error; output: ['cat', 'car', 'cart']
DIndexError: string index out of range
Attempts:
2 left
💡 Hint
Check if the DFS method correctly traverses children nodes.
🚀 Application
advanced
1:30remaining
Number of Words with Given Prefix
Given a Trie with inserted words ['apple', 'app', 'application', 'bat', 'ball'], what is the number of words that start with prefix 'app'?
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count all words that start with 'app' including the prefix itself if it is a word.
🧠 Conceptual
expert
2:00remaining
Why Use Trie for Autocomplete Instead of Hash Map?
Why is a Trie data structure preferred over a hash map for implementing an autocomplete system?
ATrie allows efficient prefix search and retrieval of all words with a given prefix, while hash maps do not support prefix queries efficiently.
BTrie uses less memory than hash maps for storing words.
CHash maps cannot store strings as keys.
DTrie automatically sorts words alphabetically, hash maps do not.
Attempts:
2 left
💡 Hint
Consider how prefix queries are handled in both data structures.

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