Bird
Raised Fist0
DSA C++programming~5 mins

Longest Word in Dictionary Using Trie in DSA C++ - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Longest Word in Dictionary Using Trie
O(N * L)
Understanding Time Complexity

We want to understand how the time needed grows when finding the longest word in a dictionary using a Trie.

How does the number of steps change as the dictionary size and word lengths increase?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

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

void dfs(TrieNode* node, TrieNode* root, std::string& current, std::string& longest) {
    if (!node) return;
    if (node != root && !node->isEnd) return;
    if (current.length() > longest.length())
        longest = current;
    for (int i = 0; i < 26; i++) {
        if (node->children[i]) {
            current.push_back('a' + i);
            dfs(node->children[i], root, current, longest);
            current.pop_back();
        }
    }
}
    

This code inserts words into a Trie and uses depth-first search to find the longest word where all prefixes are present.

Identify Repeating Operations
  • Primary operation: Insertion loops over each character of every word, and DFS recursively visits Trie nodes.
  • How many times: Insert runs once per word, each character once; DFS visits nodes up to total characters in all words.
How Execution Grows With Input

As the number of words and their lengths grow, the total characters inserted and nodes visited increase roughly with the sum of all word lengths.

Input Size (n words)Approx. Operations (sum of word lengths)
10 (avg length 5)~50 insert + ~50 DFS steps
100 (avg length 5)~500 insert + ~500 DFS steps
1000 (avg length 5)~5000 insert + ~5000 DFS steps

Pattern observation: Operations grow roughly linearly with total characters in all words combined.

Final Time Complexity

Time Complexity: O(N * L)

This means the time grows linearly with the number of words (N) times the average length of each word (L).

Common Mistake

[X] Wrong: "The search for the longest word is just O(N) because we only check each word once."

[OK] Correct: We must consider the length of each word and the Trie traversal, so the total steps depend on both number and length of words.

Interview Connect

Understanding this complexity helps you explain how tries efficiently handle prefix problems and why they are preferred over simple lists in many cases.

Self-Check

"What if we used a hash set instead of a Trie to check prefixes? How would the time complexity change?"

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