Bird
Raised Fist0
DSA Javascriptprogramming~5 mins

Word Search in Trie in DSA Javascript - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Word Search in Trie
O(m)
Understanding Time Complexity

When searching for a word in a Trie, we want to know how long it takes as the word gets longer.

We ask: How does the search time grow when the word length increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function searchWord(root, word) {
  let node = root;
  for (let char of word) {
    if (!node.children[char]) {
      return false;
    }
    node = node.children[char];
  }
  return node.isEndOfWord === true;
}
    

This code checks if a given word exists in the Trie by following each character step-by-step.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over each character in the word.
  • How many times: Once for each character in the word (word length).
How Execution Grows With Input

As the word gets longer, the search checks more characters one by one.

Input Size (word length)Approx. Operations
1010 character checks
100100 character checks
10001000 character checks

Pattern observation: The number of operations grows directly with the word length.

Final Time Complexity

Time Complexity: O(m)

This means the search time grows linearly with the length of the word being searched.

Common Mistake

[X] Wrong: "Searching a word in a Trie takes time proportional to the number of words stored."

[OK] Correct: The search depends only on the length of the word, not how many words are in the Trie.

Interview Connect

Understanding this helps you explain why Tries are efficient for prefix and word searches, a common topic in coding interviews.

Self-Check

"What if the Trie nodes used arrays instead of hash maps for children? How would the time complexity change?"

Practice

(1/5)
1. What is the main purpose of using a Trie data structure in word search?
easy
A. To efficiently store and search words by their prefixes
B. To sort words alphabetically
C. To store words in a hash table
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.
  2. Step 2: Identify Trie usage

    It allows quick prefix-based search by traversing nodes matching characters.
  3. Final Answer:

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

    Trie = prefix search [OK]
Hint: Trie is all about prefix-based fast word search [OK]
Common Mistakes:
  • Confusing Trie with hash tables
  • Thinking Trie sorts words
  • Assuming Trie does arithmetic
2. Which of the following is the correct way to check if a word exists in a Trie in JavaScript?
easy
A. Use a loop to traverse nodes matching each character and check end flag
B. Use Array.includes(word) on the Trie object
C. Use JSON.stringify on Trie and search substring
D. Use Math.max on character codes of the word

Solution

  1. Step 1: Understand Trie search method

    Search involves traversing nodes for each character and checking if the word ends at last node.
  2. Step 2: Eliminate incorrect options

    Array.includes and JSON.stringify are not suitable for Trie structure. Math.max is unrelated.
  3. Final Answer:

    Use a loop to traverse nodes matching each character and check end flag -> Option A
  4. Quick Check:

    Traverse nodes + check end = correct search [OK]
Hint: Traverse each character node and check end flag [OK]
Common Mistakes:
  • Using array methods on Trie
  • Trying to convert Trie to string
  • Applying math functions on words
3. What will be the output of the following code snippet?
class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }
  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) node.children[char] = new TrieNode();
      node = node.children[char];
    }
    node.isEnd = true;
  }
  search(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) return false;
      node = node.children[char];
    }
    return node.isEnd;
  }
}

const trie = new Trie();
trie.insert('cat');
trie.insert('car');
console.log(trie.search('cat'));
console.log(trie.search('cap'));
medium
A. false false
B. false true
C. true false
D. true true

Solution

  1. Step 1: Insert words 'cat' and 'car'

    Both words are added character by character, marking end nodes for 't' and 'r'.
  2. Step 2: Search 'cat' and 'cap'

    'cat' exists with isEnd true, 'cap' path breaks at 'p' missing node, returns false.
  3. Final Answer:

    true false -> Option C
  4. Quick Check:

    Search 'cat' = true, 'cap' = false [OK]
Hint: Check inserted words and search path carefully [OK]
Common Mistakes:
  • Assuming 'cap' exists after inserting 'car'
  • Confusing isEnd flag
  • Ignoring missing child nodes
4. Identify the bug in the following Trie search method and select the fix:
search(word) {
  let node = this.root;
  for (const char of word) {
    if (!node.children[char]) return false;
    node = node.children[char];
  }
  return true;
}
medium
A. Return false at the end instead of true
B. Add a check for empty word before loop
C. Change for loop to while loop
D. Return node.isEnd instead of true to confirm full word match

Solution

  1. Step 1: Analyze current search return

    Returns true if path exists but does not check if word ends here.
  2. Step 2: Correct return value

    Must return node.isEnd to confirm the word is complete, not just prefix.
  3. Final Answer:

    Return node.isEnd instead of true to confirm full word match -> Option D
  4. Quick Check:

    Check isEnd flag to confirm word end [OK]
Hint: Always check isEnd flag to confirm full word [OK]
Common Mistakes:
  • Returning true without checking isEnd
  • Changing loop type unnecessarily
  • Ignoring empty word cases
5. Given a list of words, how can you use a Trie to find all words that start with a given prefix efficiently? Choose the best approach.
hard
A. Sort words and use binary search on prefix
B. Insert all words into Trie, traverse prefix nodes, then collect all descendant words
C. Use a hash map with prefix keys for direct lookup
D. Check each word in list if it starts with prefix using string methods

Solution

  1. Step 1: Insert all words into Trie

    Build Trie so each word is represented by a path of nodes.
  2. Step 2: Traverse prefix nodes and collect words

    Find node matching prefix end, then recursively collect all words below it.
  3. Step 3: Compare other options

    Sorting and binary search is possible but less efficient for many queries. Hash maps need many keys. Checking each word is slow.
  4. Final Answer:

    Insert all words into Trie, traverse prefix nodes, then collect all descendant words -> Option B
  5. Quick Check:

    Trie + prefix traversal = efficient prefix search [OK]
Hint: Use Trie prefix traversal then gather descendant words [OK]
Common Mistakes:
  • Ignoring Trie traversal for prefix
  • Using slow linear search for prefix
  • Confusing hash map with Trie
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