Bird
Raised Fist0
DSA C++programming

Longest Word in Dictionary Using Trie in DSA C++

Choose your learning style10 modes available
Mental Model
We build a tree where each path from root to a node forms a prefix of words. We find the longest word where every prefix is also a word.
Analogy: Imagine a tree of building blocks where each block adds a letter. We only keep paths where every partial stack is a valid word, like building a tower with stable layers.
root
 ↓
 t -> r -> i -> e
 ↑    ↑    ↑    ↑
 w    e    e    null
Dry Run Walkthrough
Input: words = ["a", "app", "ap", "apply", "apple", "appl"]
Goal: Find the longest word where all prefixes are also in the list
Step 1: Insert 'a' into trie
root -> a[isWord=true] -> null
Why: Start building trie with first word
Step 2: Insert 'ap' into trie
root -> a[isWord=true] -> p[isWord=true] -> null
Why: Add second word, mark prefix 'ap' as word
Step 3: Insert 'app' into trie
root -> a[true] -> p[true] -> p[true] -> null
Why: Add 'app' and mark its node as word
Step 4: Insert 'appl' into trie
root -> a[true] -> p[true] -> p[true] -> l[true] -> null
Why: Add 'appl' and mark node as word
Step 5: Insert 'apple' into trie
root -> a[true] -> p[true] -> p[true] -> l[true] -> e[true] -> null
Why: Add 'apple' and mark node as word
Step 6: Insert 'apply' into trie
root -> a[true] -> p[true] -> p[true] -> l[true] -> y[true] -> null
Why: Add 'apply' and mark node as word
Step 7: Search longest word where all prefixes are words
Check 'a', 'ap', 'app', 'appl', 'apple', 'apply' all prefixes true
Why: Only words with all prefixes marked as word qualify
Step 8: Choose longest word with lex order tie-break
Longest words: 'apple' and 'apply', choose 'apple' (lex smaller)
Why: Return longest valid word with smallest lex order
Result:
apple
Annotated Code
DSA C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct TrieNode {
    TrieNode* children[26] = {nullptr};
    bool isWord = false;
};

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

    void insert(const string& word) {
        TrieNode* curr = root;
        for (char c : word) {
            int idx = c - 'a';
            if (!curr->children[idx])
                curr->children[idx] = new TrieNode();
            curr = curr->children[idx];
        }
        curr->isWord = true;
    }

    void dfs(TrieNode* node, string& path, string& longest) {
        if (!node->isWord && node != root) return; // only continue if prefix is word

        if (path.length() > longest.length() ||
            (path.length() == longest.length() && path < longest)) {
            longest = path;
        }

        for (int i = 0; i < 26; i++) {
            if (node->children[i]) {
                path.push_back('a' + i);
                dfs(node->children[i], path, longest);
                path.pop_back();
            }
        }
    }
};

string longestWord(vector<string>& words) {
    Trie trie;
    for (const string& w : words) {
        trie.insert(w);
    }
    string longest = "";
    string path = "";
    trie.dfs(trie.root, path, longest);
    return longest;
}

int main() {
    vector<string> words = {"a", "app", "ap", "apply", "apple", "appl"};
    cout << longestWord(words) << "\n";
    return 0;
}
if (!curr->children[idx]) curr->children[idx] = new TrieNode();
create child node if missing to build trie path
curr = curr->children[idx];
advance current node to child for next letter
curr->isWord = true;
mark node as end of a valid word
if (!node->isWord && node != root) return;
stop DFS if prefix is not a word (except root)
if (path.length() > longest.length() || (path.length() == longest.length() && path < longest)) { longest = path; }
update longest word if current path is longer or lex smaller
for (int i = 0; i < 26; i++) { if (node->children[i]) { path.push_back('a' + i); dfs(node->children[i], path, longest); path.pop_back(); } }
explore all children recursively to find longest valid word
OutputSuccess
apple
Complexity Analysis
Time: O(N * L) because we insert N words each of length L and DFS visits nodes once
Space: O(N * L) for trie nodes storing all words' letters
vs Alternative: Compared to sorting and checking prefixes in array (O(N L log N)), trie offers efficient prefix checks in O(L)
Edge Cases
empty list
returns empty string as no words exist
DSA C++
if (!node->isWord && node != root) return;
single letter words only
returns the lex smallest single letter word
DSA C++
if (path.length() > longest.length() || (path.length() == longest.length() && path < longest)) { longest = path; }
words with missing prefixes
skips words whose prefixes are not all words
DSA C++
if (!node->isWord && node != root) return;
When to Use This Pattern
When asked to find the longest word with all prefixes present, use a trie to efficiently check prefixes and find the answer by DFS.
Common Mistakes
Mistake: Not checking if all prefixes are words before continuing DFS
Fix: Add condition to stop DFS if current prefix node is not marked as word
Mistake: Not updating longest word correctly when lengths tie
Fix: Compare lex order when lengths are equal to pick smallest word
Summary
Build a trie from words and find the longest word where every prefix is also a word.
Use when you need to find words with all prefixes present efficiently.
The key is to stop exploring paths where prefixes are missing and track longest valid word with lex order tie-break.

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