Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trie Autocomplete Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of inserting words into a Trie
What is the output of the following code that inserts words into a Trie and then prints the children of the root node?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isEndOfWord = true;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('car');
trie.insert('dog');
console.log(Object.keys(trie.root.children));
A['c', 'd']
B['cat', 'car', 'dog']
C['c', 'a', 'd']
D['car', 'dog']
Attempts:
2 left
💡 Hint
Look at the first letters of the inserted words and what keys the root node holds.
❓ Predict Output
intermediate
2:00remaining
Output of searching a prefix in a Trie
What does the following code print when searching for the prefix 'ca' in the Trie?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isEndOfWord = true;
  }

  startsWith(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) {
        return false;
      }
      node = node.children[char];
    }
    return true;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('car');
trie.insert('dog');
console.log(trie.startsWith('ca'));
Aundefined
Bfalse
Ctrue
DTypeError
Attempts:
2 left
💡 Hint
Check if the prefix 'ca' exists in the inserted words.
🔧 Debug
advanced
3:00remaining
Find the error in the autocomplete function
The following autocomplete function is supposed to return all words in the Trie that start with a given prefix. What error will it cause when run?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isEndOfWord = true;
  }

  autocomplete(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) {
        return [];
      }
      node = node.children[char];
    }
    const results = [];
    function dfs(currentNode, path) {
      if (currentNode.isEndOfWord) {
        results.push(path);
      }
      for (const child in currentNode.children) {
        dfs(currentNode.children[child], path + child);
      }
    }
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('car');
trie.insert('dog');
console.log(trie.autocomplete('ca'));
ARangeError: Maximum call stack size exceeded
BTypeError: currentNode.children is undefined
CReferenceError: dfs is not defined
DNo error, outputs ['cat', 'car']
Attempts:
2 left
💡 Hint
Check if the dfs function is defined and called correctly.
❓ Predict Output
advanced
2:00remaining
Output of autocomplete with no matching prefix
What is the output of the autocomplete function when searching for prefix 'do' after inserting 'cat', 'car', and 'dog'?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isEndOfWord = true;
  }

  autocomplete(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) {
        return [];
      }
      node = node.children[char];
    }
    const results = [];
    function dfs(currentNode, path) {
      if (currentNode.isEndOfWord) {
        results.push(path);
      }
      for (const child in currentNode.children) {
        dfs(currentNode.children[child], path + child);
      }
    }
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('car');
trie.insert('dog');
console.log(trie.autocomplete('do'));
A['cat', 'car', 'dog']
B['dog']
C[]
Dundefined
Attempts:
2 left
💡 Hint
Check which inserted words start with 'do'.
🧠 Conceptual
expert
2:30remaining
Why use a Trie for Autocomplete?
Which of the following is the best reason to use a Trie data structure for implementing an autocomplete system?
ATries allow fast prefix searches by sharing common prefixes among words, reducing search time compared to scanning all words.
BTries use less memory than hash tables because they store only unique words without duplicates.
CTries automatically sort words alphabetically without extra processing, unlike arrays.
DTries are easier to implement than arrays or hash tables for storing words.
Attempts:
2 left
💡 Hint
Think about how Tries store prefixes and how that helps autocomplete.

Practice

(1/5)
1. What is the main purpose of using a Trie in an autocomplete system?
easy
A. To efficiently store and search prefixes of words
B. To sort words alphabetically
C. To count the frequency 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: Relate Trie to autocomplete functionality

    Autocomplete needs to find 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 A
  4. Quick Check:

    Trie = prefix search [OK]
Hint: Trie is built for prefix matching, perfect for autocomplete [OK]
Common Mistakes:
  • Confusing Trie with sorting data structure
  • Thinking Trie encrypts data
  • Assuming Trie counts word frequency only
2. Which of the following is the correct way to insert a word "cat" into a Trie node in JavaScript?
easy
A. node.children.push('c');
B. node.children['c'] = new TrieNode();
C. node['c'] = 'cat';
D. node.add('cat');

Solution

  1. Step 1: Understand Trie node structure

    Each Trie node has a children object mapping characters to child nodes, so to insert 'c', we assign a new TrieNode to node.children['c'].
  2. Step 2: Check each option's correctness

    node.children['c'] = new TrieNode(); correctly assigns a new TrieNode to the character key. Options B, C, and D do not follow the standard Trie insertion method.
  3. Final Answer:

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

    Insert char by assigning new TrieNode in children map [OK]
Hint: Use children map with character keys for Trie insertion [OK]
Common Mistakes:
  • Using array push instead of map assignment
  • Assigning string instead of TrieNode
  • Calling undefined add method
3. Given the following code snippet for searching words with prefix "app" in a Trie, what will be the output?
const trie = new Trie();
trie.insert("apple");
trie.insert("app");
trie.insert("application");
const results = trie.searchPrefix("app");
console.log(results);
medium
A. ["apple", "application"]
B. ["app"]
C. []
D. ["apple", "app", "application"]

Solution

  1. Step 1: Insert words into Trie

    Words "apple", "app", and "application" are inserted, so all prefixes starting with "app" exist in the Trie.
  2. Step 2: Search for prefix "app"

    The searchPrefix method returns all words starting with "app", which includes all three inserted words.
  3. Final Answer:

    ["apple", "app", "application"] -> Option D
  4. Quick Check:

    All words with prefix "app" returned [OK]
Hint: Search prefix returns all words starting with it [OK]
Common Mistakes:
  • Expecting only exact matches
  • Ignoring shorter word "app" itself
  • Assuming empty result if prefix is a word
4. The following code tries to insert words into a Trie but throws an error. What is the bug?
class TrieNode {
  constructor() {
    this.children = [];
    this.isEnd = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }
  insert(word) {
    let node = this.root;
    for (let char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isEnd = true;
  }
}

const trie = new Trie();
trie.insert("dog");
medium
A. children should be an object, not an array
B. isEnd should be initialized to true
C. Missing return statement in insert method
D. for loop should use index instead of for-of

Solution

  1. Step 1: Analyze children data structure

    children is initialized as an empty array, but characters are used as keys, which are strings, not numeric indices.
  2. Step 2: Identify correct data structure for children

    children should be an object (map) to use string keys like 'd', 'o', 'g'. Using array causes undefined behavior and errors.
  3. Final Answer:

    children should be an object, not an array -> Option A
  4. Quick Check:

    Use object for children keys [OK]
Hint: Use object for children to map chars, not array [OK]
Common Mistakes:
  • Using array for children with string keys
  • Setting isEnd incorrectly
  • Thinking loop type causes error
5. You want to build an autocomplete system that returns the top 2 most frequent words starting with a prefix. Which modification to a Trie node helps achieve this efficiently?
hard
A. Use an array instead of object for children
B. Store only the full words at leaf nodes
C. Store a frequency count and maintain a sorted list of top words at each node
D. Store the entire dictionary at each node

Solution

  1. Step 1: Understand requirement for top frequent words

    To quickly return top 2 frequent words for any prefix, each node should track frequency info and top words under it.
  2. Step 2: Choose data structure modification

    Storing frequency counts and maintaining a sorted list of top words at each node allows fast retrieval without full traversal.
  3. Final Answer:

    Store a frequency count and maintain a sorted list of top words at each node -> Option C
  4. Quick Check:

    Frequency + top words per node = efficient autocomplete [OK]
Hint: Keep top words and frequencies at nodes for fast autocomplete [OK]
Common Mistakes:
  • Storing full dictionary at each node wastes memory
  • Using arrays for children slows lookup
  • Ignoring frequency info for ranking
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