Bird
Raised Fist0
DSA Typescriptprogramming~5 mins

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

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

We want to understand how the time needed to find the longest word using a Trie grows as the dictionary size increases.

Specifically, how the operations scale when building and searching the Trie.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class TrieNode {
  children: Map = new Map();
  isWord: boolean = false;
}

function insert(root: TrieNode, word: string): void {
  let node = root;
  for (const char of word) {
    if (!node.children.has(char)) node.children.set(char, new TrieNode());
    node = node.children.get(char)!;
  }
  node.isWord = true;
}
    

This code inserts words into a Trie, letter by letter, marking the end of each word.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each character of every word to insert into the Trie.
  • How many times: For each of the n words, we loop through its length m characters.
How Execution Grows With Input

As the number of words (n) and their average length (m) grow, the total operations increase roughly by n times m.

Input Size (n words, avg length m)Approx. Operations
10 words, length 5~50 operations
100 words, length 5~500 operations
1000 words, length 5~5000 operations

Pattern observation: Operations grow linearly with both number of words and their length.

Final Time Complexity

Time Complexity: O(n * m)

This means the time grows proportionally to the total number of characters in all words combined.

Common Mistake

[X] Wrong: "Inserting all words into a Trie is just O(n) because we only loop over words once."

[OK] Correct: Each word has multiple characters, so we actually loop over every character in every word, making it O(n * m), not just O(n).

Interview Connect

Understanding this complexity helps you explain how Tries efficiently handle many words and why they are preferred for prefix-based problems.

Self-Check

What if we changed the data structure to a simple array and searched for the longest word by checking 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 efficiently store and search words by their prefixes
B. To sort words alphabetically
C. To count the total number of words
D. To reverse the words quickly

Solution

  1. Step 1: Understand Trie usage

    A Trie stores words by breaking them into characters and linking nodes for prefixes.
  2. Step 2: Connect Trie to longest word search

    This structure allows quick prefix checks, which helps find the longest word built from other words.
  3. Final Answer:

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

    Trie = prefix search [OK]
Hint: Trie is best for prefix-based word searches [OK]
Common Mistakes:
  • Thinking Trie sorts words alphabetically
  • Confusing Trie with simple arrays
  • Assuming Trie counts words only
2. Which of the following TypeScript code snippets correctly initializes a Trie node with children and an end-of-word flag?
easy
A. class TrieNode { children: Map = new Map(); isEnd: boolean = false; }
B. class TrieNode { children: string[] = []; isEnd: number = 0; }
C. class TrieNode { children: object = {}; isEnd: string = 'false'; }
D. class TrieNode { children: Map = new Map(); isEnd: boolean = true; }

Solution

  1. Step 1: Check children type

    Children should map characters (string) to TrieNode objects, so Map is correct.
  2. Step 2: Check isEnd flag type

    isEnd should be boolean to mark word end, so boolean = false is correct.
  3. Final Answer:

    class TrieNode { children: Map = new Map(); isEnd: boolean = false; } -> Option A
  4. Quick Check:

    Correct types = class TrieNode { children: Map = new Map(); isEnd: boolean = false; } [OK]
Hint: Use Map and boolean for TrieNode [OK]
Common Mistakes:
  • Using array instead of Map for children
  • Using wrong types for isEnd flag
  • Mixing key and value types in Map
3. Given the following TypeScript code snippet that inserts words into a Trie and finds the longest word, what will be the output?
const words = ["a", "app", "apple", "apply", "ap"];
const trie = new Trie();
words.forEach(word => trie.insert(word));
console.log(trie.findLongestWord());
medium
A. "a"
B. "apply"
C. "apple"
D. "app"

Solution

  1. Step 1: Insert words into Trie

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

    "app" has all prefixes present: "a", "ap", "app". "apple" and "apply" require "appl" which is not a word in the list.
  3. Final Answer:

    "app" -> Option D
  4. Quick Check:

    Longest word with all prefixes = "app" [OK]
Hint: Choose longest word with all prefixes present, lex smallest if tie [OK]
Common Mistakes:
  • Choosing "apple" or "apply" without checking if "appl" is a word
  • Ignoring that intermediate prefixes like "appl" must be full words
  • Picking the overall longest word without prefix validation
4. Consider this buggy TypeScript code snippet for inserting words into a Trie:
insert(word: string) {
  let node = this.root;
  for (const char of word) {
    node = node.children.get(char);
    if (!node.children.has(char)) {
      node.children.set(char, new TrieNode());
    }
  }
  node.isEnd = true;
}
What is the main issue causing a runtime error?
medium
A. The loop does not iterate over all characters
B. The isEnd flag is set before inserting nodes
C. node.children.get(char) can return undefined, causing node to be undefined
D. The children map is not initialized

Solution

  1. Step 1: Analyze node update inside loop

    node.children.get(char) may return undefined if key missing, but code assumes it returns TrieNode.
  2. Step 2: Identify cause of runtime error

    If undefined assigned to node, next iteration fails accessing children of undefined.
  3. Final Answer:

    node.children.get(char) can return undefined, causing node to be undefined -> Option C
  4. Quick Check:

    Undefined node from get() causes error [OK]
Hint: Check if get() can return undefined before assignment [OK]
Common Mistakes:
  • Ignoring possibility of undefined from Map.get()
  • Assuming loop skips characters
  • Confusing isEnd flag placement
5. You have a list of words: ["w", "wo", "wor", "worl", "world", "banana", "ban", "bana", "banan"]. Using a Trie, which word will be the longest word in the dictionary where every prefix is also a word in the list?
hard
A. "banana"
B. "world"
C. "banan"
D. "worl"

Solution

  1. Step 1: Check prefixes for "world"

    Prefixes: "w", "wo", "wor", "worl" all exist in list.
  2. Step 2: Check prefixes for "banana" and "banan"

    "banana" and "banan" are missing shorter prefixes like "b" and "ba" which are not in the list.
  3. Step 3: Compare valid longest words

    "world" is longest with all prefixes present; others longer but invalid.
  4. Final Answer:

    "world" -> Option B
  5. Quick Check:

    Longest word with all prefixes = "world" [OK]
Hint: Check all prefixes exist; longest valid word wins [OK]
Common Mistakes:
  • Choosing "banana" ignoring missing prefix like "b"
  • Confusing similar prefixes
  • Not verifying all prefixes exist
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