Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in C#: Dictionary Children, O(L) Operations

Practice O(L) Read the full explanation

A trie (pronounced "try"), or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each of its children adds one more letter to that prefix. Words that begin the same way share the same path from the root, so a trie can tell whether a word was added, or whether any added word starts a certain way, in time that depends only on the length of the word asked about. Autocomplete and spell checkers work this way.

Implement the class Trie:

  • Trie() creates an empty trie.
  • insert(word) adds the string word to the trie.
  • search(word) returns true if word was inserted before, and false otherwise.
  • startsWith(prefix) returns true if some inserted word starts with prefix, and false otherwise. A word counts as a prefix of itself.

The input is a list of operations, applied in order to one new trie. The output lists what the search and startsWith calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
    insert("apple")
    search("apple")
    search("app")
    startsWith("app")
    insert("app")
    search("app")
Output: true false true true
Explanation:
"apple" was inserted, so search("apple") is true.
"app" is only the beginning of "apple": search("app") is false, but startsWith("app") is true.
After insert("app"), search("app") is true.

Example 2:

Input:
    insert("car")
    insert("cart")
    startsWith("ca")
    search("ca")
    startsWith("cat")
    search("cart")
Output: true false false true
Explanation: Both words start with "ca", but "ca" itself was never inserted. No word starts with "cat".

Example 3:

Input:
    insert("dog")
    insert("dog")
    search("dog")
    startsWith("dog")
    search("do")
    startsWith("dogs")
    search("dogs")
Output: true true false false false
Explanation: Inserting "dog" a second time changes nothing. "dog" is a prefix of itself, so startsWith("dog") is true. Nothing longer than "dog" was inserted.

 

Constraints:

  • 1 <= word.length, prefix.length <= 30
  • word and prefix consist of lowercase English letters, a to z.
  • At most 105 calls in total are made to insert, search and startsWith.

Note:

Each operation should run in O(L) time, where L is the length of its word or prefix.

STEP 1 OF 18
    Ctrl + Enter to check

    C# · TRIES

    Implement Trie Prefix Tree in C#, explained

    Problem overview

    A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each child adds one more letter to it. Words that start the same way share the same path from the root. You implement a class Trie with three methods:

    • Insert(string word) adds a word.
    • Search(string word) returns true only if exactly that word was inserted before.
    • StartsWith(string prefix) returns true if some inserted word begins with prefix. A word counts as a prefix of itself.

    After Insert("apple"), Search("apple") is true, but Search("app") is false because "app" was never inserted as a word, while StartsWith("app") is true. After Insert("app"), Search("app") becomes true. Inserting the same word twice changes nothing. The words and prefixes are 1 to 30 lowercase letters, and each operation should take O(L) time, where L is the length of the word or prefix.

    The lesson has you write two classes: TrieNode, for one node, and Trie, which owns the root and the three methods.

    Approach: one node per prefix, a flag for word ends

    Storing the words in a list makes every query scan the list. A hash set answers Search quickly, but it can't answer StartsWith without checking every word. A trie answers both by walking down from the root, one letter per level, so the cost depends only on the length of the word asked about, not on how many words are stored.

    Each TrieNode has two fields:

    • children, a dictionary from a letter to the child node for that letter. It holds only the letters that some word actually uses.
    • isEnd, a flag that is true when an inserted word ends at this node.

    The flag is needed because a node doesn't tell you whether it ends a word. After inserting "apple", the nodes for "app" and "apple" both exist, but only the "apple" node has isEnd set. The root stands for the empty prefix, and an empty trie is a root with no children.

    All three operations walk the same way. Insert creates any missing nodes along the path and marks the last one. Search and StartsWith create nothing: they return false as soon as a letter has no child. They differ only at the end. Search returns the last node's isEnd, while StartsWith returns true, because every node in the trie lies on the path of some inserted word.

    Inserting "apple" creates 5 nodes below the root, so the trie has 6 nodes. Inserting "app" afterwards creates none and only sets a flag, so the count stays 6. Inserting "apt" adds one node for "t" and makes it 7.

    Step by step

    1. Declare children in TrieNode as a public Dictionary<char, TrieNode> set to a new empty dictionary. Fields are private unless marked public, and Trie has to reach this one.
    2. Declare isEnd as a public bool set to false.
    3. Declare root in Trie as a new TrieNode.
    4. In Insert, start node at root and loop over the letters of word with foreach.
    5. If node.children has no key c, test with ContainsKey and store a new TrieNode under node.children[c]. No earlier word went this way, so create the path.
    6. Move down with node = node.children[c]. The child exists now, whether it was already there or was just created.
    7. After the loop, set node.isEnd = true. This marks the whole word as inserted.
    8. In Search, walk the same way but return false when a letter has no child, and finish with return node.isEnd. Reaching the node isn't enough: the path for "app" exists after inserting "apple", but no word ends there.
    9. In StartsWith, walk once more, return false at a missing letter, and finish with return true.

    The solution in C#

    class TrieNode {
        public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
        public bool isEnd = false;
    }
    class Trie {
        TrieNode root = new TrieNode();
        public void Insert(string word) {
            TrieNode node = root;
            foreach (char c in word) {
                if (!node.children.ContainsKey(c)) {
                    node.children[c] = new TrieNode();
                }
                node = node.children[c];
            }
            node.isEnd = true;
        }
        public bool Search(string word) {
            TrieNode node = root;
            foreach (char c in word) {
                if (!node.children.ContainsKey(c)) {
                    return false;
                }
                node = node.children[c];
            }
            return node.isEnd;
        }
        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;
        }
    }
    

    The C# details worth knowing:

    • A missing key throws. Reading node.children[c] for a key that isn't there throws KeyNotFoundException, unlike a Java HashMap or a Python dict.get, which give null or a default. That is why every read is guarded by ContainsKey. Assigning with node.children[c] = ... never throws: it adds the key if needed.
    • TryGetValue is the alternative. node.children.TryGetValue(c, out TrieNode next) checks and reads in one lookup. The lesson's version does two lookups per letter, which is fine at these sizes.
    • foreach (char c in word) visits the characters of a string in order. A char is a valid dictionary key.
    • Visibility. root has no modifier, so it is private to Trie. children and isEnd are public so that Trie's methods can use them. The method names are PascalCase, Insert, Search and StartsWith, as the starter code has them. Code ported from Java or Python often uses insert and startsWith, which don't match.
    • Printing a bool with Console.WriteLine gives True or False, with capital letters. The values are still the C# keywords true and false.
    • Dictionary needs using System.Collections.Generic; at the top of a standalone file.

    Complexity

    Time: O(L) per operation. Each operation does one dictionary lookup, which takes constant time on average, for each of the L letters. The number of words stored doesn't matter.

    Space: O(N) in total, where N is the number of nodes created. In the worst case, when no two words share a prefix, that is the total length of all inserted words. Shared prefixes are stored once.

    Edge cases and common mistakes

    • Empty trie. Search("a") and StartsWith("a") both return false, since the root has no children.
    • A word that is a prefix of another. With "car" and "cart" inserted, Search("car") is true and StartsWith("car") is true. Search("ca") is false and StartsWith("ca") is true.
    • A prefix that was never a word. With "dog" inserted, Search("do") is false, and StartsWith("dogs") is false because the walk runs out of nodes.
    • Duplicate inserts. Inserting "dog" twice creates the nodes once and sets the same flag twice.
    • Returning true at the end of Search. That would make Search("app") true after inserting only "apple". The final answer must be node.isEnd.
    • Forgetting to set isEnd in Insert. Every Search would then return false, even for inserted words.
    • Creating nodes while searching. Using node.children[c] = new TrieNode() in Search would grow the trie on each query and make absent words look like prefixes later.
    • Reading a missing child without ContainsKey. The walk would throw KeyNotFoundException on the first word that isn't present.

    Testing

    • Insert "apple", then Search("apple"), Search("app"), StartsWith("app"), insert "app", Search("app") give true, false, true, true.
    • Insert "car" and "cart", then StartsWith("ca"), Search("ca"), StartsWith("cat"), Search("cart") give true, false, false, true.
    • Insert "dog" twice, then Search("dog"), StartsWith("dog"), Search("do"), StartsWith("dogs"), Search("dogs") give true, true, false, false, false.
    • On an empty trie, Search("a") and StartsWith("a") give false and false.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free