Prefix Search Using Trie in DSA C# - Time & Space Complexity
We want to understand how fast we can find words that start with a given prefix using a Trie.
The question is: how does the search time grow as the prefix length or dictionary size changes?
Analyze the time complexity of the following code snippet.
public bool StartsWith(string prefix) {
TrieNode node = root;
foreach (char c in prefix) {
if (!node.Children.ContainsKey(c)) {
return false;
}
node = node.Children[c];
}
return true;
}
This code checks if any word in the Trie starts with the given prefix by walking down nodes for each character.
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).
The time grows directly with the length of the prefix, not the total number of words stored.
| Input Size (prefix length m) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The operations increase linearly as the prefix length increases.
Time Complexity: O(m)
This means the search time depends only on the prefix length, not the number of words stored.
[X] Wrong: "The search time depends on how many words are in the Trie."
[OK] Correct: The search only follows the prefix characters, so it depends on prefix length, not total words.
Knowing that prefix search in a Trie is fast and depends on prefix length helps you explain efficient search in many applications.
"What if the Trie stored words with Unicode characters instead of just ASCII? How would the time complexity change?"
Practice
Trie data structure in prefix search?Solution
Step 1: Understand the role of Trie in prefix search
A Trie stores words in a tree-like structure where each node represents a character. This allows quick traversal to find words sharing the same prefix.Step 2: Identify the main use case
Because of this structure, Tries are mainly used to find all words starting with a given prefix efficiently.Final Answer:
To efficiently find all words that start with a given prefix -> Option CQuick Check:
Trie = prefix search efficiency [OK]
- Confusing Trie with sorting algorithms
- Thinking Trie is for arithmetic operations
- Assuming Trie stores numbers only
Solution
Step 1: Identify the correct data type for children nodes
Trie nodes store children as a map from characters to TrieNode objects. Dictionary is the correct choice in C#.Step 2: Check the other options
List<int> or int[] are incorrect because they don't map characters to nodes. String is also incorrect as children must be nodes, not strings.Final Answer:
public class TrieNode { public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>(); public bool IsEndOfWord; } -> Option AQuick Check:
Children map chars to nodes = public class TrieNode { public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>(); public bool IsEndOfWord; } [OK]
- Using List<int> instead of Dictionary
- Using array of ints instead of nodes
- Declaring children as string
var trie = new Trie();
trie.Insert("cat");
trie.Insert("car");
trie.Insert("dog");
var result = trie.SearchPrefix("ca");
Console.WriteLine(string.Join(",", result));
Assuming SearchPrefix returns all words starting with the given prefix.Solution
Step 1: Insert words into the Trie
The words "cat", "car", and "dog" are inserted. "cat" and "car" share the prefix "ca".Step 2: Search for prefix "ca"
Searching prefix "ca" returns all words starting with "ca", which are "cat" and "car".Final Answer:
cat,car -> Option AQuick Check:
Words with prefix "ca" = cat,car [OK]
- Returning only one word instead of all matches
- Confusing prefix "ca" with "car"
- Including words without the prefix
public bool StartsWith(string prefix) {
var node = root;
foreach (var ch in prefix) {
if (!node.Children.ContainsKey(ch))
return false;
node = node.Children[ch];
}
return node.IsEndOfWord;
}Solution
Step 1: Understand method purpose
The method checks if any word in the Trie starts with the given prefix.Step 2: Identify the bug in return statement
Returning node.IsEndOfWord checks if prefix itself is a complete word, but prefix search should return true if prefix exists regardless of word end.Final Answer:
It should return true after traversing prefix, not check IsEndOfWord -> Option DQuick Check:
Prefix exists if traversal succeeds, no need to check IsEndOfWord [OK]
- Checking IsEndOfWord for prefix existence
- Not handling empty prefix correctly
- Using wrong loop type
GetAllWordsWithPrefix in a Trie that returns all words starting with a given prefix. Which approach correctly combines prefix traversal and word collection?Solution
Step 1: Traverse Trie to prefix node
First, move down the Trie following the prefix characters to reach the node representing the last prefix character.Step 2: Recursively collect all words from prefix node
From this node, recursively explore all child nodes to collect complete words that start with the prefix.Final Answer:
Traverse to prefix node, then recursively collect all words from that node -> Option BQuick Check:
Prefix traversal + recursion = Traverse to prefix node, then recursively collect all words from that node [OK]
- Filtering all words after collecting entire Trie
- Returning words only if prefix is a full word
- Random traversal without prefix focus
Ready to prove it?
Pass the test and this pattern moves unknown
