Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Go: Insert, Search, StartsWith

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 20
    Ctrl + Enter to check

    GO · TRIES

    Implement Trie Prefix Tree in Go, explained

    Problem overview

    A trie, 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 it. Words that begin the same way share the same path from the root, so a trie can answer questions about a word in time that depends only on the length of that word.

    The task is a Trie type with three methods: Insert(word string) adds a word, Search(word string) bool says whether that exact word was inserted, and StartsWith(prefix string) bool says whether some inserted word begins with the prefix. A word counts as a prefix of itself. Words and prefixes are 1 to 30 lowercase letters, and there are at most 100,000 calls.

    After inserting "apple", Search("apple") is true, Search("app") is false and StartsWith("app") is true. After inserting "app" as well, Search("app") becomes true. Each operation should take O(L) time, where L is the length of its argument.

    Approach: one node per prefix

    A list of words would make every search scan the list, and comparing strings costs time too. A trie replaces that with a walk. Start at the root, which stands for the empty prefix, and follow one child per letter. A word needs at most L steps to reach its node, however many words are stored.

    A path in the trie doesn't say whether a word ends there. After inserting "apple", the nodes for "a", "ap", "app", "appl" and "apple" all exist, but only the last one ends a word. So each node carries a flag, isEnd, that is set where an inserted word finishes. This flag is the entire difference between Search and StartsWith:

    • Search walks the word and then returns the flag of the node it reached.
    • StartsWith walks the prefix and returns true if the walk didn't fall off the tree, because every node of a trie lies on the path of some inserted word.

    Step by step

    1. Design the node. TrieNode has children, a map[rune]*TrieNode from each next letter to the child node, and isEnd, a bool. Ranging over a string gives runes, so the keys are runes, and the values are pointers so that a walk follows the shared nodes and not copies.
    2. Write NewTrieNode. It returns &TrieNode{children: make(map[rune]*TrieNode)}. A map must be made before anything can be stored in it. isEnd is left out and starts as false.
    3. Give Trie a root of type *TrieNode, and let Constructor return a Trie with a fresh root. An empty trie is a root with no children.
    4. Insert. Start node at the root. For each letter c of the word, create the child if node.children[c] is nil, then move down to it. After the loop, set node.isEnd = true.
    5. Search. Walk the same way, but create nothing. If a child is missing, return false. After the loop, return node.isEnd, because reaching the node isn't enough.
    6. StartsWith. The same walk over the prefix, and the answer after the loop is simply true.

    The solution in Go

    type TrieNode struct {
        children map[rune]*TrieNode
        isEnd bool
    }
    
    func NewTrieNode() *TrieNode {
        return &TrieNode{children: make(map[rune]*TrieNode)}
    }
    
    type Trie struct {
        root *TrieNode
    }
    
    func Constructor() Trie {
        return Trie{root: NewTrieNode()}
    }
    
    func (this *Trie) Insert(word string) {
        node := this.root
        for _, c := range word {
            if node.children[c] == nil {
                node.children[c] = NewTrieNode()
            }
            node = node.children[c]
        }
        node.isEnd = true
    }
    
    func (this *Trie) Search(word string) bool {
        node := this.root
        for _, c := range word {
            if node.children[c] == nil {
                return false
            }
            node = node.children[c]
        }
        return node.isEnd
    }
    
    func (this *Trie) StartsWith(prefix string) bool {
        node := this.root
        for _, c := range prefix {
            if node.children[c] == nil {
                return false
            }
            node = node.children[c]
        }
        return true
    }
    

    Inserting "apple" creates 5 nodes below the root. Inserting "app" afterwards creates none: the path exists, and only the flag on the node for "app" changes, which is what turns Search("app") from false to true. Inserting "apply" then adds one node, because it shares the path "appl" with "apple".

    Go details

    • A missing map key gives the zero value. For a map of pointers that is nil, so node.children[c] == nil means "no such child". Reading a missing key doesn't add it to the map, so Search and StartsWith never change the trie. Searching "zebra" in a trie that holds only "dog" leaves it with 3 nodes.
    • Runes as keys. for _, c := range word yields the index, which is skipped with _, and c as a rune, an integer type that is a valid map key.
    • Pointer receivers. The methods use *Trie, so t := Constructor() followed by t.Insert("a") works: Go takes the address of t for you.
    • Always use Constructor. A Trie declared as var z Trie has a nil root, and inserting into it panics. The constructor is what creates the root.
    • Struct literals with field names. Trie{root: NewTrieNode()} names the field, so the code stays correct if more fields are added later.
    • The flag defaults to false. Go gives every field its zero value, so a new node doesn't end a word until Insert says so.

    Complexity

    Time: O(L) per operation. Each of the three methods does one pass over its argument. Each step is a map lookup, which takes constant time on average, and possibly the creation of one node.

    Space: O(N) in total, where N is the total number of letters across the inserted words. In the worst case, when words share nothing, each letter gets its own node. Shared prefixes cost nothing extra.

    Edge cases and common mistakes

    • A prefix that is not a word. After inserting "car" and "cart", StartsWith("ca") is true but Search("ca") is false.
    • No word continues that way. StartsWith("cat") is false because there is no t child under "ca".
    • Inserting a word twice. Inserting "dog" twice changes nothing: the nodes exist and the flag is already true. In that trie, Search("dog") and StartsWith("dog") are true, while Search("do"), StartsWith("dogs") and Search("dogs") are false.
    • Returning true from Search when the walk succeeds. That makes Search("app") true after inserting only "apple". The answer is the flag.
    • Forgetting to set the flag. Without node.isEnd = true, no word would ever be found.
    • Not making the map. Writing to a nil map panics, so each node needs make in its constructor.
    • Creating nodes while searching. Assigning a child inside Search would make later StartsWith calls answer true for words that were never inserted.

    Testing

    • Insert "apple", then Search("apple"), Search("app"), StartsWith("app"), insert "app", Search("app"): true false true true.
    • Insert "car", "cart", then StartsWith("ca"), Search("ca"), StartsWith("cat"), Search("cart"): true false false true.
    • Insert "dog" twice, then Search("dog"), StartsWith("dog"), Search("do"), StartsWith("dogs"), Search("dogs"): true true false false false.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free