using System; using System.Collections.Generic; class TrieNode { public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>(); public bool IsWordEnd = false; } class Trie { private TrieNode root = new TrieNode(); public void Insert(string word) { var node = root; foreach (var ch in word) { if (!node.Children.ContainsKey(ch)) { node.Children[ch] = new TrieNode(); } node = node.Children[ch]; } node.IsWordEnd = true; } 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 true; } } class Program { static void Main() { var trie = new Trie(); trie.Insert("apple"); trie.Insert("app"); trie.Insert("application"); Console.WriteLine(trie.StartsWith("app")); Console.WriteLine(trie.StartsWith("appl")); Console.WriteLine(trie.StartsWith("banana")); } }
The method StartsWith returns true if the prefix exists in the Trie. Since "app", "apple", and "application" are inserted, prefixes "app" and "appl" exist, but "banana" does not.
A Trie allows prefix search in time proportional to the prefix length (k), because it traverses nodes for each character. A Hash Map storing full words requires checking all words (n) to find matches, so prefix search is O(n).
using System; using System.Collections.Generic; class Program { static void Main() { var words = new Dictionary<string, int> { {"apple", 1}, {"app", 2}, {"application", 3}, {"banana", 4} }; string prefix = "app"; foreach (var word in words.Keys) { if (word.StartsWith(prefix)) Console.WriteLine(word); } } }
The dictionary initialization is missing a semicolon after the closing brace, causing a syntax error.
Trie is best for large datasets with prefix queries because it allows fast prefix search in time proportional to prefix length and saves space by sharing prefixes.
using System; using System.Collections.Generic; class TrieNode { public Dictionary<char, TrieNode> Children = new Dictionary<char, TrieNode>(); public bool IsWordEnd = false; } class Trie { private TrieNode root = new TrieNode(); public void Insert(string word) { var node = root; foreach (var ch in word) { if (!node.Children.ContainsKey(ch)) { node.Children[ch] = new TrieNode(); } node = node.Children[ch]; } node.IsWordEnd = true; } 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 true; } } class Program { static void Main() { var trie = new Trie(); var map = new Dictionary<string, int>(); string[] words = {"cat", "car", "cart", "dog", "dove"}; foreach (var w in words) { trie.Insert(w); map[w] = w.Length; } Console.WriteLine(trie.StartsWith("ca")); Console.WriteLine(map.ContainsKey("car")); Console.WriteLine(trie.StartsWith("do")); Console.WriteLine(map.ContainsKey("cow")); } }
The Trie contains prefixes "ca" and "do" from inserted words. The map contains keys "car" but not "cow".
