Trie Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie runs in O(m) time and O(n*m) space, in C# as in every other language.
- ✓System.Collections.Generic has no trie. The node is Dictionary<char, Node> for open alphabets or Node[26] for a fixed one; SortedDictionary<char, Node> buys you ordered enumeration at a log factor per edge.
- ✓TryGetValue(ch, out var next) is mandatory; ContainsKey followed by the indexer is two hashes and gets flagged every time.
- ✓The C# trap: The trie is ordinal by construction, and the rest of C# is not. string.StartsWith(prefix) and string.Compare default to the CURRENT CULTURE, so a culture-aware check disagrees with your trie: under a Hungarian culture certain letter pairs (dzs, cs, sz) compare as single units, under a Turkish culture i/I and the dotless i do not case-map the way ordinal comparison assumes, and ignorable characters such as a soft hyphen or a zero-width joiner compare as absent, meaning "coop".StartsWith("coop") can be true culturally while your trie, which walked the soft hyphen as a real edge, says false.
- ✓Dictionary<char, Node> is fast for a value-type key because EqualityComparer<char>.Default is devirtualised and inlined by the JIT, so there is no interface call per edge; boxing never happens here.
What Trie actually is
Trie in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Generic;
#nullable enable
public sealed class Trie
{
private sealed class Node
{
public readonly Dictionary<char, Node> Children = new();
public bool IsWord;
}
private readonly Node _root = new();
public void Insert(string word)
{
var node = _root;
foreach (var ch in word)
{
// miss path is two probes; CollectionsMarshal.GetValueRefOrAddDefault
// collapses it to one on .NET 6+
if (!node.Children.TryGetValue(ch, out var next))
{
next = new Node();
node.Children[ch] = next;
}
node = next;
}
node.IsWord = true;
}
private Node? Walk(ReadOnlySpan<char> prefix) // no Substring allocation
{
var node = _root;
foreach (var ch in prefix)
{
// one probe, not ContainsKey plus indexer
if (!node.Children.TryGetValue(ch, out var next)) return null;
node = next;
}
return node;
}
public bool Contains(string word) => Walk(word) is { IsWord: true };
public bool StartsWith(string prefix) => Walk(prefix) is not null;
public IEnumerable<string> WithPrefix(string prefix)
{
var start = Walk(prefix);
if (start is null) yield break;
var stack = new Stack<(Node Node, string Acc)>();
stack.Push((start, prefix));
while (stack.TryPop(out var frame))
{
if (frame.Node.IsWord) yield return frame.Acc;
foreach (var (ch, child) in frame.Node.Children)
{
stack.Push((child, frame.Acc + ch));
}
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Trie?
System.Collections.Generic has no trie. The node is Dictionary<char, Node> for open alphabets or Node[26] for a fixed one; SortedDictionary<char, Node> buys you ordered enumeration at a log factor per edge. Two BCL pieces are worth pulling in: ReadOnlySpan<char> so a prefix walk never allocates a Substring, and System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault, which does the find-or-insert on a Dictionary in a single probe instead of TryGetValue followed by an indexer set. On NuGet, rm.Trie and KTrie are the maintained options.
What is the most common C# mistake when implementing Trie?
The trie is ordinal by construction, and the rest of C# is not. string.StartsWith(prefix) and string.Compare default to the CURRENT CULTURE, so a culture-aware check disagrees with your trie: under a Hungarian culture certain letter pairs (dzs, cs, sz) compare as single units, under a Turkish culture i/I and the dotless i do not case-map the way ordinal comparison assumes, and ignorable characters such as a soft hyphen or a zero-width joiner compare as absent, meaning "coop".StartsWith("coop") can be true culturally while your trie, which walked the soft hyphen as a real edge, says false. Always pass StringComparison.Ordinal in any fallback path, and normalise input once (string.Normalize) before inserting rather than hoping the two agree.
How does Trie actually perform in C#?
Dictionary<char, Node> is fast for a value-type key because EqualityComparer<char>.Default is devirtualised and inlined by the JIT, so there is no interface call per edge; boxing never happens here. Size is the problem: a Dictionary instance is roughly 80 bytes before its buckets and entries arrays, so millions of one-child nodes are mostly hash table. Node[26] is a 24-byte array header plus 26 references and one bounds-checked load. Walking with ReadOnlySpan<char> removes the per-call Substring allocation, and tiered JIT means the first few thousand descents run unoptimised. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.