0
0
DSA Javascriptprogramming~5 mins

Prefix Search Using Trie in DSA Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Prefix Search Using Trie
O(m)
Understanding Time Complexity

We want to understand how fast we can find words that start with a given prefix using a Trie.

How does the search time change as the prefix or dictionary grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = false;
  }
}

function prefixSearch(root, prefix) {
  let node = root;
  for (const char of prefix) {
    if (!node.children[char]) return false;
    node = node.children[char];
  }
  return true;
}
    

This code checks if any word in the Trie starts with the given prefix by walking down the Trie nodes.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each character of the prefix.
  • How many times: Exactly once per character in the prefix (length m).
How Execution Grows With Input

As the prefix gets longer, the search takes more steps, one per character.

Input Size (prefix length m)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The time grows linearly with the prefix length.

Final Time Complexity

Time Complexity: O(m)

This means the search time depends only on the prefix length, not the number of words stored.

Common Mistake

[X] Wrong: "The search time depends on the total number of words in the Trie."

[OK] Correct: The search only follows the prefix characters, so it depends on prefix length, not total words.

Interview Connect

Knowing how prefix search scales helps you explain efficient word lookup in real apps like autocomplete.

Self-Check

"What if we changed the prefix search to return all words starting with the prefix? How would the time complexity change?"