C#
Trie
Data Structures
Programming
Tutorial

How to create a trie in c

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Creating a trie in C# is a rewarding task that helps you understand how to efficiently store strings for fast prefix-based searches. A trie, also known as a prefix tree, is a tree-like data structure that efficiently stores and retrieves keys in a dataset of strings. Here, I'll guide you through the process of creating a trie in C#, cover the necessary components, and provide technical explanations along with examples.

Trie Structure

A trie consists of nodes where each node represents a single character of a string. The root node is empty, and a path from the root to a leaf (or a node marked as end-of-word) represents a string stored in the trie. This data structure supports operations such as insertion, search, and deletion more efficiently compared to other data structures for certain types of datasets.

The main components of a trie node include:

  • Character Storage: Storing a character or key value.
  • Children: A collection (usually a hash map or an array) to point to the next node.
  • End-of-Word Marker: A boolean flag to indicate the end of a valid string.

Example Implementation

Below is a basic example of how to implement a trie in C#:

  • Contains a dictionary of children nodes.
  • Holds a boolean flag IsEndOfWord to indicate the end of a valid word.
  • Has methods for inserting words (Insert ), searching exact words (Search ), and checking for prefixes (StartsWith ).
  • Iterates through each character of the word.
  • Traverses the nodes and creates new nodes when necessary.
  • Marks the last node of the word as IsEndOfWord .
  • Similar to insert, but returns false if any character is missing from the path.
  • Checks if any word in the trie starts with a given prefix.
  • Performance: Trie operations generally have a time complexity proportional to the length of the string being manipulated, making them fast for prefix searches.
  • Space Usage: Tries can consume a significant amount of memory, especially if keys are long or shared prefixes are few.
  • Applications: Useful in autocomplete systems, IP routing, spell-checkers, and similar applications.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.