Implement a trie (prefix tree) for string matching?
Short answer: public class TrieNode { public TrieNode[] Children = new TrieNode[26]; public bool IsEnd = false; } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void Insert(string word) { TrieNode node = root; foreach (char c in word) { int idx = c - 'a'; if (node.Children[idx] == null) node.Children[idx] = new TrieNode(); node = node.Children[idx]; } node.IsEnd = true; } public bool…
Explain a bit more
Search(string word) { TrieNode node = SearchNode(word); return node != null && node.IsEnd; } public bool StartsWith(string prefix) { return SearchNode(prefix) != null; } private TrieNode SearchNode(string word) { TrieNode node = root; foreach (char c in word) { int idx = c - 'a'; if (node.Children[idx] == null) return null; Follow on: node = node.Children[idx]; } return node; } } Explanation: Standard trie with insert, search, and prefix checking.
Example code
public class TrieNode {
public TrieNode[] Children = new TrieNode[26];
public bool IsEnd = false;
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void Insert(string word) {
TrieNode node = root;
foreach (char c in word) {
int idx = c - 'a';
if (node.Children[idx] == null)
node.Children[idx] = new TrieNode();
node = node.Children[idx];
}
node.IsEnd = true;
}
public bool Search(string word) {
TrieNode node = SearchNode(word);
return node != null && node.IsEnd;
}
public bool StartsWith(string prefix) {
return SearchNode(prefix) != null;
}
private TrieNode SearchNode(string word) {
TrieNode node = root;
foreach (char c in word) {
int idx = c - 'a';
if (node.Children[idx] == null) return null; Follow on: node = node.Children[idx];
}
return node;
}
} Explanation: Standard trie with insert, search, and prefix checking.
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png