Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Prefix Search Using Trie in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prefix Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Prefix Search Result
What is the output of the following code that inserts words into a Trie and searches for words with prefix 'app'?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = 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.isEnd = true;
  }

  startsWith(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) {
        return [];
      }
      node = node.children[char];
    }
    const results = [];
    const dfs = (currNode, path) => {
      if (currNode.isEnd) results.push(path);
      for (const c in currNode.children) {
        dfs(currNode.children[c], path + c);
      }
    };
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
['apple', 'app', 'application', 'bat', 'ball'].forEach(w => trie.insert(w));
console.log(trie.startsWith('app'));
A["app", "apple", "application"]
B["apple", "application"]
C["app", "application"]
D["bat", "ball"]
Attempts:
2 left
💡 Hint
Think about all words starting exactly with 'app' including the prefix itself.
🧠 Conceptual
intermediate
1:30remaining
Number of Nodes in Trie After Insertions
After inserting the words ['cat', 'car', 'cart', 'dog'] into an empty Trie, how many nodes does the Trie contain?
A8
B10
C7
D9
Attempts:
2 left
💡 Hint
Count shared prefixes only once.
🔧 Debug
advanced
1:30remaining
Identify the Error in Trie Search Method
What error does the following Trie search method produce when searching for a prefix that does not exist?
DSA Javascript
startsWith(prefix) {
  let node = this.root;
  for (const char of prefix) {
    node = node.children[char];
  }
  return node !== undefined;
}
ASyntaxError due to missing return statement
BReturns false correctly
CTypeError: Cannot read property 'children' of undefined
DAlways returns true
Attempts:
2 left
💡 Hint
What happens if node.children[char] is undefined and you try to access its children?
🚀 Application
advanced
1:30remaining
Find All Words with Prefix in Trie
Given a Trie with words inserted, which method correctly returns all words starting with a given prefix?
ATraverse to prefix node, then DFS to collect all words from there
BReturn all words in Trie and filter those starting with prefix
CCheck only if prefix is a word in Trie and return it
DReturn empty list if prefix length is less than 3
Attempts:
2 left
💡 Hint
Think about efficient search using Trie structure.
❓ Predict Output
expert
2:30remaining
Output of Complex Trie Prefix Search
What is the output of the following code snippet?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = 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.isEnd = true;
  }

  startsWith(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) return [];
      node = node.children[char];
    }
    const results = [];
    const dfs = (currNode, path) => {
      if (currNode.isEnd) results.push(path);
      for (const c in currNode.children) {
        dfs(currNode.children[c], path + c);
      }
    };
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
['team', 'teach', 'test', 'tester', 'testing'].forEach(w => trie.insert(w));
console.log(trie.startsWith('te'));
A["tester", "testing"]
B["team", "teach", "test", "tester", "testing"]
C["team", "teach"]
D["test", "tester", "testing"]
Attempts:
2 left
💡 Hint
All words starting with 'te' should be included.

Practice

(1/5)
1. What is the main purpose of using a Trie data structure in prefix search?
easy
A. To efficiently find all words starting with a given prefix
B. To sort words alphabetically
C. To store numbers in ascending order
D. To perform arithmetic operations quickly

Solution

  1. Step 1: Understand Trie usage

    A Trie stores words in a tree-like structure where each node represents a character.
  2. Step 2: Identify prefix search benefit

    This structure allows quick traversal to find all words sharing a prefix without scanning all words.
  3. Final Answer:

    To efficiently find all words starting with a given prefix -> Option A
  4. Quick Check:

    Trie = prefix search efficiency [OK]
Hint: Trie nodes represent characters for fast prefix lookup [OK]
Common Mistakes:
  • Confusing Trie with sorting algorithms
  • Thinking Trie stores numbers only
  • Assuming Trie is for arithmetic
2. Which of the following is the correct way to initialize an empty Trie node in JavaScript?
easy
A. const node = [];
B. const node = new Map();
C. const node = null;
D. const node = { children: {}, isEnd: false };

Solution

  1. Step 1: Understand Trie node structure

    A Trie node typically has a children object to hold next characters and a boolean to mark word end.
  2. Step 2: Match correct initialization

    const node = { children: {}, isEnd: false }; correctly creates an object with children as empty object and isEnd as false.
  3. Final Answer:

    const node = { children: {}, isEnd: false }; -> Option D
  4. Quick Check:

    Trie node = object with children and isEnd [OK]
Hint: Trie nodes use objects with children and end flag [OK]
Common Mistakes:
  • Using array instead of object for children
  • Setting node to null instead of object
  • Using Map without isEnd flag
3. What will be the output of the following code snippet?
class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = 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.isEnd = 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'));
medium
A. true
B. false
C. undefined
D. Error

Solution

  1. Step 1: Insert words into Trie

    Words 'cat', 'car', and 'dog' are inserted, creating nodes for each character.
  2. Step 2: Check prefix 'ca'

    Both 'cat' and 'car' start with 'ca', so traversal finds nodes for 'c' and 'a'.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Prefix 'ca' exists = true [OK]
Hint: If prefix matches inserted words, startsWith returns true [OK]
Common Mistakes:
  • Confusing startsWith with exact word search
  • Expecting false if prefix is partial
  • Ignoring that multiple words share prefix
4. Identify the bug in the following Trie insert method and select the fix:
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.isEnd = true;
}
medium
A. Remove node.isEnd assignment
B. Change if condition to check if child does NOT exist before creating new node
C. Initialize node as null before loop
D. Use a Map instead of object for children

Solution

  1. Step 1: Analyze insert method logic

    The code creates a new node only if node.children[char] exists, which is incorrect.
  2. Step 2: Correct condition for node creation

    We should create a new node only if node.children[char] does NOT exist to avoid overwriting existing nodes.
  3. Final Answer:

    Change if condition to check if child does NOT exist before creating new node -> Option B
  4. Quick Check:

    Insert new node only if missing [OK]
Hint: Create new child node only if it does not exist [OK]
Common Mistakes:
  • Creating new node when child already exists
  • Forgetting to mark end of word
  • Initializing node incorrectly
5. Given a list of words ['apple', 'app', 'apricot', 'banana'], how would you use a Trie to find all words starting with 'ap'? Choose the correct approach.
hard
A. Insert only words starting with 'ap' into Trie and ignore others
B. Sort the list and filter words starting with 'ap' using string methods
C. Insert all words into Trie, then traverse nodes for prefix 'ap' and collect all descendant words
D. Use a hash map to store words and check prefix by substring matching

Solution

  1. Step 1: Build Trie with all words

    Insert all words so the Trie contains complete data for prefix search.
  2. Step 2: Traverse Trie for prefix 'ap'

    Navigate nodes for 'a' then 'p', then collect all words from this subtree.
  3. Step 3: Collect descendant words

    Gather words like 'apple', 'app', and 'apricot' that share the prefix.
  4. Final Answer:

    Insert all words into Trie, then traverse nodes for prefix 'ap' and collect all descendant words -> Option C
  5. Quick Check:

    Trie + prefix traversal = all matching words [OK]
Hint: Insert all words, then traverse prefix subtree to find matches [OK]
Common Mistakes:
  • Filtering list without Trie defeats purpose
  • Ignoring words not starting with prefix during insertion
  • Using hash map instead of Trie for prefix search
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