Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Prefix Search Using Trie in DSA Typescript - 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 TypeScript code that inserts words into a Trie and searches for words starting with a prefix?
DSA Typescript
class TrieNode {
  children: Map<string, TrieNode> = new Map();
  isEndOfWord: boolean = false;
}

class Trie {
  root: TrieNode = new TrieNode();

  insert(word: string): void {
    let node = this.root;
    for (const char of word) {
      if (!node.children.has(char)) {
        node.children.set(char, new TrieNode());
      }
      node = node.children.get(char)!;
    }
    node.isEndOfWord = true;
  }

  searchPrefix(prefix: string): string[] {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children.has(char)) {
        return [];
      }
      node = node.children.get(char)!;
    }
    const results: string[] = [];
    const dfs = (currentNode: TrieNode, path: string) => {
      if (currentNode.isEndOfWord) {
        results.push(path);
      }
      for (const [char, childNode] of currentNode.children) {
        dfs(childNode, path + char);
      }
    };
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
trie.insert("apple");
trie.insert("app");
trie.insert("apex");
trie.insert("bat");
trie.insert("bath");
const result = trie.searchPrefix("ap");
console.log(result);
A["app", "apple", "apex"]
B["apple", "app", "apex"]
C["apex", "app", "apple"]
D["app", "apex"]
Attempts:
2 left
💡 Hint
Think about how the DFS collects words in alphabetical order based on children map iteration.
🧠 Conceptual
intermediate
1:00remaining
Number of Words with Given Prefix
If a Trie contains the words ["cat", "car", "cart", "dog", "dove"], how many words start with the prefix "car"?
A0
B2
C3
D1
Attempts:
2 left
💡 Hint
Count all words that begin exactly with 'car'.
🔧 Debug
advanced
1:30remaining
Identify the Bug in Trie Insertion
What error will occur when running this TypeScript code snippet for inserting a word into a Trie?
DSA Typescript
class TrieNode {
  children: Map<string, TrieNode> = new Map();
  isEndOfWord: boolean = false;
}

class Trie {
  root: TrieNode = new TrieNode();

  insert(word: string): void {
    let node = this.root;
    for (const char of word) {
      if (!node.children.has(char)) {
        node.children.set(char, new TrieNode());
      }
      node = node.children.get(char); // Bug here
    }
    node.isEndOfWord = true;
  }
}

const trie = new Trie();
trie.insert("hello");
ANo error, runs correctly
BSyntaxError: Unexpected token
CReferenceError: node is not defined
DTypeError: Cannot read property 'isEndOfWord' of undefined
Attempts:
2 left
💡 Hint
Check the return type of Map.get and how it's used.
📝 Syntax
advanced
1:30remaining
Correct Syntax for DFS in Trie Search
Which option correctly defines the DFS function inside the searchPrefix method to collect all words starting with a prefix?
DSA Typescript
dfs = (currentNode: TrieNode, path: string) => {
  if (currentNode.isEndOfWord) {
    results.push(path);
  }
  for (const [char, childNode] of currentNode.children) {
    dfs(childNode, path + char);
  }
};
A
function dfs(currentNode: TrieNode, path: string) {
  if (currentNode.isEndOfWord) {
    results.push(path);
  }
  for (const [char, childNode] of currentNode.children) {
    dfs(childNode, path + char);
  }
}
B
dfs(currentNode: TrieNode, path: string) =&gt; {
  if (currentNode.isEndOfWord) {
    results.push(path);
  }
  for (const [char, childNode] of currentNode.children) {
    dfs(childNode, path + char);
  }
};
C
const dfs = (currentNode: TrieNode, path: string) =&gt; {
  if (currentNode.isEndOfWord) {
    results.push(path);
  }
  for (const [char, childNode] of currentNode.children) {
    dfs(childNode, path + char);
  }
};
D
const dfs = function(currentNode: TrieNode, path: string) {
  if (currentNode.isEndOfWord) {
    results.push(path);
  }
  for (const [char, childNode] of currentNode.children) {
    dfs(childNode, path + char);
  }
};
Attempts:
2 left
💡 Hint
Arrow functions with const are common for nested functions in TypeScript.
🚀 Application
expert
2:30remaining
Find All Words with Prefix and Sort Alphabetically
Given a Trie with words inserted in any order, which code modification ensures that searchPrefix returns all words starting with the prefix sorted alphabetically?
DSA Typescript
searchPrefix(prefix: string): string[] {
  let node = this.root;
  for (const char of prefix) {
    if (!node.children.has(char)) {
      return [];
    }
    node = node.children.get(char)!;
  }
  const results: string[] = [];
  const dfs = (currentNode: TrieNode, path: string) => {
    if (currentNode.isEndOfWord) {
      results.push(path);
    }
    for (const [char, childNode] of currentNode.children) {
      dfs(childNode, path + char);
    }
  };
  dfs(node, prefix);
  return results;
}
AModify DFS to visit children in alphabetical order by sorting keys before recursion.
BChange Map to a JavaScript object and iterate keys sorted alphabetically.
CUse a PriorityQueue to store words during DFS and dequeue all at the end.
DSort the results array before returning: return results.sort();
Attempts:
2 left
💡 Hint
Think about controlling the order of traversal rather than sorting after collection.

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 that start with a given prefix
B. To sort words alphabetically
C. To store words in reverse order
D. To count the total number of words

Solution

  1. Step 1: Understand Trie usage

    A Trie stores words by their prefixes, allowing quick prefix-based lookups.
  2. Step 2: Identify prefix search goal

    Prefix search means finding all words starting with a given prefix efficiently.
  3. Final Answer:

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

    Trie = Prefix search [OK]
Hint: Trie is built for prefix-based fast word retrieval [OK]
Common Mistakes:
  • Confusing Trie with sorting structure
  • Thinking Trie stores words reversed
  • Assuming Trie counts total words only
2. Which of the following is the correct TypeScript syntax to define a Trie node with children as a Map and an endOfWord boolean?
easy
A. class TrieNode { children: object; endOfWord: string; constructor() { this.children = {}; this.endOfWord = ''; } }
B. class TrieNode { children: string[]; endOfWord: boolean; constructor() { this.children = []; this.endOfWord = false; } }
C. class TrieNode { children: Map; endOfWord: boolean; constructor() { this.children = new Map(); this.endOfWord = false; } }
D. class TrieNode { children: Map; endOfWord: boolean; constructor() { this.children = new Map(); this.endOfWord = false; } }

Solution

  1. Step 1: Check children type

    Children should be a Map with string keys and TrieNode values for prefix characters.
  2. Step 2: Check endOfWord type

    endOfWord is a boolean indicating if node ends a word.
  3. Final Answer:

    class TrieNode { children: Map; endOfWord: boolean; constructor() { this.children = new Map(); this.endOfWord = false; } } -> Option D
  4. Quick Check:

    Map + boolean endOfWord = class TrieNode { children: Map; endOfWord: boolean; constructor() { this.children = new Map(); this.endOfWord = false; } } [OK]
Hint: Use Map for children and boolean for endOfWord [OK]
Common Mistakes:
  • Using array instead of Map for children
  • Using wrong key type in Map
  • Setting endOfWord as string instead of boolean
3. Given the following TypeScript code snippet, what will be the output of console.log(trie.startsWith('app'))?
class TrieNode {
  children = new Map();
  endOfWord = false;
}

class Trie {
  root = new TrieNode();

  insert(word: string) {
    let node = this.root;
    for (const char of word) {
      if (!node.children.has(char)) {
        node.children.set(char, new TrieNode());
      }
      node = node.children.get(char)!;
    }
    node.endOfWord = true;
  }

  startsWith(prefix: string): boolean {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children.has(char)) return false;
      node = node.children.get(char)!;
    }
    return true;
  }
}

const trie = new Trie();
trie.insert('apple');
trie.insert('app');
trie.insert('bat');
medium
A. true
B. false
C. undefined
D. Error at runtime

Solution

  1. Step 1: Insert words into Trie

    Words 'apple', 'app', and 'bat' are inserted, so prefix 'app' exists in Trie.
  2. Step 2: Check startsWith method

    Method returns true if prefix characters exist in Trie nodes, which they do for 'app'.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Prefix 'app' found = true [OK]
Hint: If prefix inserted, startsWith returns true [OK]
Common Mistakes:
  • Confusing startsWith with search for whole word
  • Expecting false if prefix is a word itself
  • Thinking startsWith returns endOfWord status
4. The following TypeScript code tries to implement a startsWith method for a Trie but always returns false. What is the bug?
startsWith(prefix: string): boolean {
  let node = this.root;
  for (const char of prefix) {
    if (!node.children.has(char)) return false;
    node = node.children.get(char);
  }
  return false;
}
medium
A. It should check endOfWord before returning
B. It should use a for loop with index instead of for-of
C. It should return true after the loop if prefix exists
D. It should initialize node with a new TrieNode

Solution

  1. Step 1: Analyze loop behavior

    The loop correctly traverses nodes for each prefix character.
  2. Step 2: Check return statement

    Method returns false always after loop, so never returns true even if prefix found.
  3. Step 3: Fix return logic

    Return true after loop if all prefix chars found.
  4. Final Answer:

    It should return true after the loop if prefix exists -> Option C
  5. Quick Check:

    Return true after loop if prefix found [OK]
Hint: Return true after loop if prefix nodes exist [OK]
Common Mistakes:
  • Returning false at end regardless
  • Checking endOfWord unnecessarily
  • Incorrect node initialization
5. You want to extend a Trie to return all words starting with a given prefix. Which approach correctly implements this in TypeScript? A) Traverse to prefix node, then recursively collect all words below. B) Store all words in an array and filter by prefix each time. C) Use a hash map to map prefixes to words directly. D) Insert reversed words and search suffixes instead.
hard
A. Store all words in an array and filter by prefix each time.
B. Traverse to prefix node, then recursively collect all words below.
C. Use a hash map to map prefixes to words directly.
D. Insert reversed words and search suffixes instead.

Solution

  1. Step 1: Understand prefix search extension

    To get all words with prefix, first find node matching prefix.
  2. Step 2: Collect words recursively

    From prefix node, recursively traverse children to collect all complete words.
  3. Step 3: Evaluate other options

    Filtering array or hash map is less efficient; reversed words search suffixes, not prefixes.
  4. Final Answer:

    Traverse to prefix node, then recursively collect all words below. -> Option B
  5. Quick Check:

    Recursive traversal from prefix node = Traverse to prefix node, then recursively collect all words below. [OK]
Hint: Find prefix node, then DFS to collect words [OK]
Common Mistakes:
  • Filtering all words each time (slow)
  • Using hash map without prefix traversal
  • Confusing prefix with suffix 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