Bird
Raised Fist0
DSA C++programming

Word Search in Trie in DSA C++

Choose your learning style10 modes available
Mental Model
A trie stores words by sharing common prefixes, making it easy to check if a word exists by following the path of letters.
Analogy: Imagine a tree where each branch is a letter, and walking down branches spells out words. To find a word, you just follow the branches matching each letter.
root
 ↓
 a -> p -> p -> l -> e [end]
      ↓
      e -> null

Each arrow points to the next letter node. The [end] marks a complete word.
Dry Run Walkthrough
Input: Insert words: "apple", "app", then search for "app"
Goal: Check if the word "app" exists in the trie after inserting "apple" and "app"
Step 1: Insert 'apple' letter by letter
root -> a -> p -> p -> l -> e [end]
root is empty initially
Why: We build the path for 'apple' so we can find it later
Step 2: Insert 'app' letter by letter, reusing existing nodes
root -> a -> p -> p [end]
           ↓
           l -> e [end]
Why: We reuse 'a', 'p', 'p' nodes and mark 'p' as end for 'app'
Step 3: Search for 'app' by following nodes
root -> a -> p -> p [end]
search ends at node marked end
Why: Finding 'app' means all letters exist and last node marks word end
Result:
root -> a -> p -> p [end]
           ↓
           l -> e [end]
Search result: true
Annotated Code
DSA C++
#include <iostream>
#include <string>
using namespace std;

class TrieNode {
public:
    TrieNode* children[26];
    bool isEndOfWord;

    TrieNode() {
        for (int i = 0; i < 26; i++) children[i] = nullptr;
        isEndOfWord = false;
    }
};

class Trie {
private:
    TrieNode* root;
public:
    Trie() { root = new TrieNode(); }

    void insert(const string& word) {
        TrieNode* curr = root;
        for (char c : word) {
            int index = c - 'a';
            if (!curr->children[index])
                curr->children[index] = new TrieNode();
            curr = curr->children[index]; // advance curr to next letter node
        }
        curr->isEndOfWord = true; // mark end of word
    }

    bool search(const string& word) {
        TrieNode* curr = root;
        for (char c : word) {
            int index = c - 'a';
            if (!curr->children[index])
                return false; // letter missing, word not found
            curr = curr->children[index]; // advance curr to next letter node
        }
        return curr->isEndOfWord; // check if last node marks word end
    }
};

int main() {
    Trie trie;
    trie.insert("apple");
    trie.insert("app");
    cout << boolalpha << trie.search("app") << endl;
    return 0;
}
curr = curr->children[index]; // advance curr to next letter node
advance curr pointer to next letter node to build or traverse path
curr->isEndOfWord = true; // mark end of word
mark current node as end of a valid word
if (!curr->children[index]) return false; // letter missing, word not found
stop search early if next letter node does not exist
return curr->isEndOfWord; // check if last node marks word end
confirm word exists only if last node marks end
OutputSuccess
true
Complexity Analysis
Time: O(m) because we process each of the m letters in the word once during insert or search
Space: O(m) for insert because we may create up to m new nodes for a new word
vs Alternative: Compared to searching words in a list (O(n*m)), trie search is faster as it depends only on word length, not number of words
Edge Cases
search for a word not inserted
search returns false because path breaks before end
DSA C++
if (!curr->children[index]) return false; // letter missing, word not found
insert empty string
marks root as end of word, allowing empty word search
DSA C++
curr->isEndOfWord = true; // mark end of word
search for prefix that is not a word
returns false because last node is not marked end
DSA C++
return curr->isEndOfWord; // check if last node marks word end
When to Use This Pattern
When you need to quickly check if words or prefixes exist in a large set, use a trie because it shares common prefixes and speeds up search.
Common Mistakes
Mistake: Not marking the end of word node, causing search to fail for words that are prefixes of others
Fix: Always set isEndOfWord = true at the last node of inserted words
Mistake: Returning true if all letters exist without checking isEndOfWord, causing false positives
Fix: Check isEndOfWord to confirm the word ends exactly at that node
Summary
Stores words by shared prefixes to enable fast word search.
Use when you want quick lookup of words or prefixes in a dictionary.
The key is marking nodes that end words to distinguish full words from prefixes.

Practice

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

Solution

  1. Step 1: Understand Trie structure

    A Trie stores characters of words in a tree where each node represents a character, allowing prefix sharing.
  2. Step 2: Identify Trie use in word search

    Because words share prefixes, Trie allows fast prefix-based search, making word search efficient.
  3. Final Answer:

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

    Trie = prefix search [OK]
Hint: Trie is best for prefix-based word search [OK]
Common Mistakes:
  • Confusing Trie with sorting structures
  • Thinking Trie stores words linearly
  • Assuming Trie is for arithmetic
2. Which of the following is the correct way to declare a Trie node class in C++ for word search?
easy
A. class TrieNode { public: TrieNode* children[26]; bool isEndOfWord; };
B. class TrieNode { int data; TrieNode* next; };
C. struct TrieNode { vector<int> children; bool end; };
D. class TrieNode { char letter; TrieNode* left; TrieNode* right; };

Solution

  1. Step 1: Check Trie node structure for word search

    Trie nodes typically have an array of pointers for 26 letters and a boolean to mark word end.
  2. Step 2: Match with options

    class TrieNode { public: TrieNode* children[26]; bool isEndOfWord; }; matches this structure exactly with children array and isEndOfWord flag.
  3. Final Answer:

    class TrieNode { public: TrieNode* children[26]; bool isEndOfWord; }; -> Option A
  4. Quick Check:

    Trie node = children array + end flag [OK]
Hint: Trie nodes have 26 children pointers and end flag [OK]
Common Mistakes:
  • Using linked list pointers instead of array
  • Using vector<int> instead of pointers
  • Confusing binary tree node with Trie node
3. What will be the output of the following C++ code snippet that inserts words into a Trie and searches for "cat"?
class TrieNode {
public:
    TrieNode* children[26] = {nullptr};
    bool isEndOfWord = false;
};

class Trie {
public:
    TrieNode* root;
    Trie() { root = new TrieNode(); }
    void insert(string word) {
        TrieNode* node = root;
        for (char c : word) {
            int index = c - 'a';
            if (!node->children[index])
                node->children[index] = new TrieNode();
            node = node->children[index];
        }
        node->isEndOfWord = true;
    }
    bool search(string word) {
        TrieNode* node = root;
        for (char c : word) {
            int index = c - 'a';
            if (!node->children[index])
                return false;
            node = node->children[index];
        }
        return node->isEndOfWord;
    }
};

int main() {
    Trie trie;
    trie.insert("cat");
    trie.insert("car");
    trie.insert("dog");
    cout << (trie.search("cat") ? "Found" : "Not Found") << endl;
    return 0;
}
medium
A. Runtime Error
B. Found
C. Compilation Error
D. Not Found

Solution

  1. Step 1: Insert words "cat", "car", "dog" into Trie

    Each word is inserted character by character, creating nodes and marking end of word for last character.
  2. Step 2: Search for "cat" in Trie

    Traversal finds nodes for 'c', 'a', 't' and confirms isEndOfWord is true, so returns true.
  3. Final Answer:

    Found -> Option B
  4. Quick Check:

    Inserted word found = Found [OK]
Hint: Search returns true if end flag is set after traversal [OK]
Common Mistakes:
  • Not marking isEndOfWord true on insert
  • Returning true without checking end flag
  • Off-by-one errors in indexing
4. Identify the bug in the following Trie search function and select the correct fix:
bool search(string word) {
    TrieNode* node = root;
    for (char c : word) {
        int index = c - 'a';
        if (node->children[index])
            return false;
        node = node->children[index];
    }
    return node->isEndOfWord;
}
medium
A. Add a check for null root pointer before loop
B. Remove the return statement inside the loop
C. Change 'node = node->children[index];' to 'node = node->children[index + 1];'
D. Change 'if (node->children[index])' to 'if (!node->children[index])'

Solution

  1. Step 1: Analyze the if condition inside loop

    The condition 'if (node->children[index]) return false;' wrongly returns false if child exists, which is opposite logic.
  2. Step 2: Correct the condition to check if child does NOT exist

    It should be 'if (!node->children[index]) return false;' to return false when path breaks.
  3. Final Answer:

    Change 'if (node->children[index])' to 'if (!node->children[index])' -> Option D
  4. Quick Check:

    Check for missing child = return false [OK]
Hint: Return false if child node is missing, not if present [OK]
Common Mistakes:
  • Returning false when child exists
  • Ignoring null pointer checks
  • Incorrect index calculation
5. Given a list of words: ["apple", "app", "application", "bat", "bath", "batman"], how can a Trie be used to efficiently find all words starting with the prefix "app"? Choose the best approach.
hard
A. Insert all words into Trie, then traverse nodes for 'a'->'p'->'p' and collect all descendant words
B. Sort the list and perform binary search for prefix "app"
C. Use a hash map to store all words and check prefix by substring
D. Store words in a linked list and scan each word for prefix match

Solution

  1. Step 1: Insert all words into Trie

    Each word is inserted character by character, building a prefix tree.
  2. Step 2: Traverse Trie nodes for prefix "app"

    Follow nodes for 'a', 'p', 'p' to reach prefix node, then collect all words below it.
  3. Step 3: Collect descendant words

    Perform DFS or BFS from prefix node to gather all words starting with "app" efficiently.
  4. Final Answer:

    Insert all words into Trie, then traverse nodes for 'a'->'p'->'p' and collect all descendant words -> Option A
  5. Quick Check:

    Trie prefix traversal + collect descendants = Insert all words into Trie, then traverse nodes for 'a'->'p'->'p' and collect all descendant words [OK]
Hint: Traverse prefix nodes then gather descendants in Trie [OK]
Common Mistakes:
  • Using sorting instead of Trie for prefix search
  • Checking prefix by substring on all words
  • Scanning linked list inefficiently
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