Bird
Raised Fist0
DSA Javaprogramming~20 mins

Word Search in Trie in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trie Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Trie Word Search
What is the output of the following Java code that inserts words into a Trie and searches for a specific word?
DSA Java
class TrieNode {
    TrieNode[] children = new TrieNode[26];
    boolean isEnd = false;
}

class Trie {
    TrieNode root = new TrieNode();

    void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int idx = c - 'a';
            if (node.children[idx] == null) {
                node.children[idx] = new TrieNode();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }

    boolean search(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int idx = c - 'a';
            if (node.children[idx] == null) {
                return false;
            }
            node = node.children[idx];
        }
        return node.isEnd;
    }
}

public class Main {
    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        trie.insert("app");
        trie.insert("application");
        System.out.println(trie.search("app"));
        System.out.println(trie.search("appl"));
    }
}
Atrue\nfalse
Btrue\ntrue
Cfalse\nfalse
Dfalse\ntrue
Attempts:
2 left
💡 Hint
Remember that search returns true only if the word is fully inserted and marked as an end.
🧠 Conceptual
intermediate
1:30remaining
Trie Node Children Count
After inserting the words ["cat", "car", "cart", "dog"] into an empty Trie, how many children does the root node have?
A1
B3
C4
D2
Attempts:
2 left
💡 Hint
Count distinct first letters of inserted words.
🔧 Debug
advanced
2:00remaining
Identify the Error in Trie Search
What error will the following Java code produce when searching for a word not inserted in the Trie?
DSA Java
class TrieNode {
    TrieNode[] children = new TrieNode[26];
    boolean isEnd = false;
}

class Trie {
    TrieNode root = new TrieNode();

    void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int idx = c - 'a';
            if (node.children[idx] == null) {
                node.children[idx] = new TrieNode();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }

    boolean search(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int idx = c - 'a';
            node = node.children[idx];
        }
        return node != null && node.isEnd;
    }
}

public class Main {
    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("hello");
        System.out.println(trie.search("hey"));
    }
}
ANo error, returns false
BArrayIndexOutOfBoundsException
CNullPointerException
DCompilation error
Attempts:
2 left
💡 Hint
Check if the code verifies children before accessing.
📝 Syntax
advanced
1:30remaining
Correct Syntax for Trie Insert Method
Which option shows the correct syntax for inserting a word into a Trie in Java?
A
for (char c : word.toCharArray()) {
    int idx = c - 'a';
    if (node.children[idx] == null) {
        node.children[idx] = new TrieNode();
    }
    node = node.children[idx];
}
node.isEnd = true;
B
for (char c in word) {
    int idx = c - 'a';
    if (node.children[idx] == null) {
        node.children[idx] = new TrieNode();
    }
    node = node.children[idx];
}
node.isEnd = true;
C
for (int i = 0; i < word.length(); i++) {
    int idx = word.charAt(i) - 'a';
    if (node.children[idx] == null) {
        node.children[idx] = new TrieNode();
    }
    node = node.children[idx];
}
node.isEnd = true;
D
for (char c : word.toCharArray()) {
    int idx = c - 'a';
    if (node.children[idx] != null) {
        node.children[idx] = new TrieNode();
    }
    node = node.children[idx];
}
node.isEnd = true;
Attempts:
2 left
💡 Hint
Java uses for-each with colon, not 'in'. Also check condition for creating new nodes.
🚀 Application
expert
2:30remaining
Number of Words with Given Prefix in Trie
Given a Trie with words inserted: ["test", "team", "teach", "tent", "toast"], what is the number of words in the Trie that start with the prefix "te"?
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Count all words starting with 'te' from the list.

Practice

(1/5)
1. What is the main purpose of using a Trie data structure in word search problems?
easy
A. To perform arithmetic operations on words
B. To sort words alphabetically
C. To store words in a linked list
D. To efficiently store and search words by their prefixes

Solution

  1. Step 1: Understand Trie structure

    A Trie stores characters of words in a tree-like structure where each node represents a character.
  2. Step 2: Identify Trie usage in word search

    It allows quick prefix-based search, making it efficient to find words starting with given letters.
  3. Final Answer:

    To efficiently store and search words by their prefixes -> Option D
  4. Quick Check:

    Trie = prefix search [OK]
Hint: Trie is all about prefix-based fast word search [OK]
Common Mistakes:
  • Confusing Trie with sorting data structures
  • Thinking Trie stores words as linked lists
  • Assuming Trie performs arithmetic on words
2. Which of the following is the correct way to declare a Trie node class in Java?
easy
A. class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; }
B. class TrieNode { int val; TrieNode children; boolean isWord; }
C. class TrieNode { String val; TrieNode[] children = new TrieNode[26]; }
D. class TrieNode { char val; List<TrieNode> children; boolean isWord; }

Solution

  1. Step 1: Check data types for Trie node

    Each node stores a character, an array of 26 children for letters a-z, and a boolean to mark word end.
  2. Step 2: Validate options

    class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } matches this structure exactly with char val, TrieNode[] children of size 26, and boolean isWord.
  3. Final Answer:

    class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } -> Option A
  4. Quick Check:

    Correct TrieNode declaration = class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } [OK]
Hint: Trie nodes use char + array of 26 children + boolean flag [OK]
Common Mistakes:
  • Using int or String instead of char for node value
  • Using single child instead of array for children
  • Using List instead of fixed-size array for children
3. What will be the output of the following Java code snippet that inserts words into a Trie and searches for "cat"?
class TrieNode {
  TrieNode[] children = new TrieNode[26];
  boolean isWord = false;
}

class Trie {
  TrieNode root = new TrieNode();

  void insert(String word) {
    TrieNode node = root;
    for (char c : word.toCharArray()) {
      int idx = c - 'a';
      if (node.children[idx] == null) node.children[idx] = new TrieNode();
      node = node.children[idx];
    }
    node.isWord = true;
  }

  boolean search(String word) {
    TrieNode node = root;
    for (char c : word.toCharArray()) {
      int idx = c - 'a';
      if (node.children[idx] == null) return false;
      node = node.children[idx];
    }
    return node.isWord;
  }
}

public class Main {
  public static void main(String[] args) {
    Trie trie = new Trie();
    trie.insert("cat");
    trie.insert("car");
    System.out.println(trie.search("cat"));
    System.out.println(trie.search("cap"));
  }
}
medium
A. false false
B. true false
C. true true
D. false true

Solution

  1. Step 1: Insert words "cat" and "car" into Trie

    Both words are inserted character by character, marking the last node's isWord as true.
  2. Step 2: Search for "cat" and "cap"

    "cat" exists with isWord true, so search returns true. "cap" path is missing 'p' node, so returns false.
  3. Final Answer:

    true false -> Option B
  4. Quick Check:

    Inserted words found = true, missing word = false [OK]
Hint: Search returns true only if full word path and isWord true [OK]
Common Mistakes:
  • Assuming partial prefix returns true
  • Not marking isWord correctly on insert
  • Confusing character indexing in children array
4. Identify the bug in the following Trie search method and choose the correct fix:
boolean search(String word) {
  TrieNode node = root;
  for (int i = 0; i <= word.length(); i++) {
    int idx = word.charAt(i) - 'a';
    if (node.children[idx] == null) return false;
    node = node.children[idx];
  }
  return node.isWord;
}
medium
A. Initialize idx before loop
B. Return true inside the loop
C. Change loop condition to i < word.length()
D. Remove return statement inside loop

Solution

  1. Step 1: Analyze loop boundary

    The loop runs from i = 0 to i <= word.length(), which causes index out of bounds at last iteration.
  2. Step 2: Fix loop condition

    Changing condition to i < word.length() prevents accessing invalid index and correctly iterates over characters.
  3. Final Answer:

    Change loop condition to i < word.length() -> Option C
  4. Quick Check:

    Loop boundary fix prevents index error [OK]
Hint: Loop over string chars with i < length, not <= length [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Trying to fix by moving idx initialization
  • Removing return inside loop causing wrong logic
5. Given a 2D board of characters and a list of words, which approach best uses a Trie to efficiently find all words present on the board? A sample board:
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Words: ["oath", "pea", "eat", "rain"]
hard
A. Build a Trie from words, then DFS on board checking prefixes in Trie
B. Check each word by scanning entire board without Trie
C. Use a hash set for words and scan board rows only
D. Sort words and board rows, then binary search each word

Solution

  1. Step 1: Build Trie from given words

    Insert all words into a Trie to enable prefix checking during search.
  2. Step 2: Perform DFS on board cells

    From each cell, explore neighbors recursively, checking if current path matches any prefix in Trie to prune search.
  3. Step 3: Collect words found when Trie node marks word end

    This approach efficiently finds all words without redundant searches.
  4. Final Answer:

    Build a Trie from words, then DFS on board checking prefixes in Trie -> Option A
  5. Quick Check:

    Trie + DFS = efficient word search on board [OK]
Hint: Use Trie for prefix pruning during DFS on board [OK]
Common Mistakes:
  • Searching words one by one scanning whole board
  • Ignoring prefix pruning causing slow search
  • Using sorting and binary search which doesn't fit 2D board
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