Bird
Raised Fist0
DSA C++programming~10 mins

Longest Word in Dictionary Using Trie in DSA C++ - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to insert a word into the Trie.

DSA C++
void insert(string word) {
    TrieNode* node = root;
    for (char c : word) {
        int index = c - 'a';
        if (node->children[[1]] == nullptr) {
            node->children[index] = new TrieNode();
        }
        node = node->children[index];
    }
    node->isEnd = true;
}
Drag options to blanks, or click blank then click option'
Aindex
Bc
Cword
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Using the character 'c' directly as an index causes errors.
Using the whole word instead of the character index.
2fill in blank
medium

Complete the code to check if a node marks the end of a word.

DSA C++
bool isEndOfWord(TrieNode* node) {
    return node->[1];
}
Drag options to blanks, or click blank then click option'
AwordEnd
BisWord
Cend
DisEnd
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect variable names like 'isWord' or 'wordEnd'.
3fill in blank
hard

Fix the error in the DFS function to find the longest word.

DSA C++
void dfs(TrieNode* node, string& current, string& longest) {
    if (!node || !node->[1]) return;
    if (current.length() > longest.length()) {
        longest = current;
    }
    for (int i = 0; i < 26; i++) {
        if (node->children[i] && node->children[i]->isEnd) {
            current.push_back('a' + i);
            dfs(node->children[i], current, longest);
            current.pop_back();
        }
    }
}
Drag options to blanks, or click blank then click option'
AisWord
BisEnd
Cend
DwordEnd
Attempts:
3 left
💡 Hint
Common Mistakes
Checking the wrong variable for word end.
Not stopping DFS when node is null.
4fill in blank
hard

Fill both blanks to build the longest word using DFS traversal.

DSA C++
void dfs(TrieNode* node, string& current, string& longest) {
    if (!node || !node->[1]) return;
    if (current.length() > longest.length() || (current.length() == longest.length() && current < longest)) {
        longest = current;
    }
    for (int i = 0; i < 26; i++) {
        if (node->children[i] && node->children[i]->[2]) {
            current.push_back('a' + i);
            dfs(node->children[i], current, longest);
            current.pop_back();
        }
    }
}
Drag options to blanks, or click blank then click option'
AisEnd
BisWord
Cend
DwordEnd
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for the two blanks.
Using variables that do not exist in the TrieNode.
5fill in blank
hard

Fill all three blanks to complete the function that finds the longest word in the dictionary.

DSA C++
string longestWord(vector<string>& words) {
    Trie trie;
    for (auto& word : words) {
        trie.[1](word);
    }
    string longest = "";
    string current = "";
    trie.[2](trie.root, current, longest);
    return longest;
}

class Trie {
public:
    TrieNode* root;
    Trie() {
        root = new TrieNode();
    }
    void [3](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->isEnd = true;
    }
    void dfs(TrieNode* node, string& current, string& longest) {
        if (!node || !node->isEnd) return;
        if (current.length() > longest.length() || (current.length() == longest.length() && current < longest)) {
            longest = current;
        }
        for (int i = 0; i < 26; i++) {
            if (node->children[i] && node->children[i]->isEnd) {
                current.push_back('a' + i);
                dfs(node->children[i], current, longest);
                current.pop_back();
            }
        }
    }
};
Drag options to blanks, or click blank then click option'
Ainsert
Bdfs
CinsertWord
Dsearch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'search' instead of 'insert' to add words.
Confusing function names for DFS.

Practice

(1/5)
1. What is the main purpose of using a Trie data structure when finding the longest word in a dictionary?
easy
A. To sort words alphabetically
B. To reverse the words in the dictionary
C. To count the total number of words
D. To efficiently store and search words by their prefixes

Solution

  1. Step 1: Understand Trie usage

    A Trie stores words by their prefixes, allowing quick prefix checks.
  2. Step 2: Relate to longest word search

    Finding the longest word with all prefixes present is easier with prefix-based storage.
  3. Final Answer:

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

    Trie = prefix search [OK]
Hint: Trie stores prefixes for fast word checks [OK]
Common Mistakes:
  • Thinking Trie sorts words alphabetically
  • Confusing Trie with simple arrays
  • Assuming Trie counts words only
2. Which of the following is the correct way to declare a Trie node class in C++ for lowercase English letters?
easy
A. class TrieNode { public: vector<TrieNode> children; bool isEnd; TrieNode() { isEnd = false; } };
B. class TrieNode { public: TrieNode* children[26]; bool isEnd; TrieNode() { for(int i=0; i<26; i++) children[i] = nullptr; isEnd = false; } };
C. class TrieNode { public: TrieNode* children[52]; bool isEnd; TrieNode() { for(int i=0; i<52; i++) children[i] = nullptr; isEnd = false; } };
D. class TrieNode { public: int children[26]; bool isEnd; TrieNode() { for(int i=0; i<26; i++) children[i] = 0; isEnd = true; } };

Solution

  1. Step 1: Check children type and size

    Children should be pointers to TrieNode, size 26 for lowercase letters.
  2. Step 2: Check initialization

    Initialize all children to nullptr and isEnd to false.
  3. Final Answer:

    class TrieNode { public: TrieNode* children[26]; bool isEnd; TrieNode() { for(int i=0; i<26; i++) children[i] = nullptr; isEnd = false; } }; -> Option B
  4. Quick Check:

    Pointer array size 26, initialized null [OK]
Hint: Use pointer array size 26 for lowercase letters [OK]
Common Mistakes:
  • Using int array instead of pointers
  • Wrong array size (52 instead of 26)
  • Not initializing children to nullptr
3. What will be the output of the following code snippet that inserts words into a Trie and finds the longest word where all prefixes exist? vector<string> words = {"a", "ap", "app", "appl", "apple", "apply"}; // After building Trie and searching longest word cout << longestWord(words) << endl;
medium
A. "apple"
B. "apply"
C. "appl"
D. "app"

Solution

  1. Step 1: Insert all words into Trie

    Words "a", "ap", "app", "appl", "apple", "apply" are inserted.
  2. Step 2: Find longest word with all prefixes present

    "apple" and "apply" both have all prefixes present, but "apple" comes first lexicographically.
  3. Final Answer:

    "apple" -> Option A
  4. Quick Check:

    Longest word with all prefixes = "apple" [OK]
Hint: Check all prefixes exist; choose longest lex smallest [OK]
Common Mistakes:
  • Choosing "apply" ignoring lex order
  • Choosing shorter words like "app"
  • Not verifying all prefixes exist
4. Identify the error in this Trie insertion code snippet for lowercase English letters: void insert(TrieNode* root, 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->isEnd = true; }
medium
A. No error; code is correct
B. Incorrect calculation of index from character
C. Missing initialization of root node before insertion
D. Not marking the end of word after insertion

Solution

  1. Step 1: Check index calculation

    Index is correctly calculated as c - 'a' for lowercase letters.
  2. Step 2: Verify insertion and end marking

    Children nodes are created if null, and isEnd is set true after insertion.
  3. Final Answer:

    No error; code is correct -> Option A
  4. Quick Check:

    Insertion logic correct [OK]
Hint: Check index and isEnd marking carefully [OK]
Common Mistakes:
  • Miscomputing index for uppercase letters
  • Forgetting to mark isEnd true
  • Not initializing root before use (outside snippet)
5. Given a list of words, how would you modify the Trie-based approach to find the longest word where every prefix is also a valid word, but now the dictionary may contain uppercase and lowercase letters mixed? Choose the best approach.
hard
A. Ignore case and treat uppercase and lowercase as same during insertion
B. Convert all words to lowercase before inserting into Trie and searching
C. Use a Trie with 52 children per node to handle both cases distinctly
D. Use a hash map instead of Trie for faster prefix checks

Solution

  1. Step 1: Understand case sensitivity

    Uppercase and lowercase letters differ; need to distinguish them in Trie.
  2. Step 2: Adjust Trie structure

    Use 52 children per node (26 lowercase + 26 uppercase) to store all letters distinctly.
  3. Final Answer:

    Use a Trie with 52 children per node to handle both cases distinctly -> Option C
  4. Quick Check:

    Handle case by expanding Trie size [OK]
Hint: Expand Trie children to 52 for mixed case [OK]
Common Mistakes:
  • Converting all to lowercase loses case info
  • Ignoring case causes wrong matches
  • Using hash map loses prefix tree benefits
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