Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Scala: 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 18
    Ctrl + Enter to check

    SCALA · TRIES

    Implement Trie Prefix Tree in Scala, 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 the trie can say 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.

    The lesson asks for a class Trie with three methods:

    • insert(word) adds a word and returns nothing;
    • search(word) returns true only if exactly that word was inserted before;
    • startsWith(prefix) returns true if some inserted word starts with prefix. A word counts as a prefix of itself.

    After insert("apple"), search("apple") is true, but search("app") is false while startsWith("app") is true. After insert("app"), search("app") is true as well. After insert("car") and insert("cart"), startsWith("ca") is true, search("ca") is false and startsWith("cat") is false. Inserting "dog" twice changes nothing. Each operation should run in O(L) time, where L is the length of its word or prefix.

    Approach: one node per prefix, one flag per word

    Storing the words in a list or a set would answer search quickly, but startsWith would have to check every stored word. The trie answers both questions by walking down from the root, one letter per level.

    Each node has two parts. The first is a map from a letter to the child node for that letter, and it contains only the letters that some word uses. The second is a flag, isEnd, which is true on a node where an inserted word ends. The flag is needed because after inserting "apple" the nodes for "app" and "apple" both exist, and only the flag tells you that "apple" was inserted and "app" was not.

    The root stands for the empty prefix. An empty trie is a root with no children.

    All three operations walk the same way. insert creates missing nodes along the path and sets the flag at the end. search and startsWith create nothing: they stop with false as soon as a letter has no child. They differ only at the end of the walk. search returns the node's isEnd flag, because reaching the node is not enough. startsWith returns true, because reaching the node proves that some inserted word passes through it: every node of a trie lies on the path of an inserted word.

    Step by step

    1. Write TrieNode. val children is a new empty scala.collection.mutable.Map[Char, TrieNode](). A val only means that children always refers to the same map, and a mutable map can still grow.
    2. Add the flag. var isEnd = false is a var because it changes when a word ends here.
    3. Create the root. Inside Trie, val root = new TrieNode().
    4. insert starts at the root. var node = root follows the word down.
    5. Loop over the letters. for (c <- word) goes one level down per letter.
    6. Create the missing child. If node.children has no key c, store new TrieNode() under it with node.children(c) = new TrieNode(). This adds the entry to a mutable map.
    7. Move down. node = node.children(c). The child exists now, whether it was there before or was just created.
    8. Mark the end. After the loop, node.isEnd = true. This is what makes the whole word count as inserted.
    9. search repeats the walk. The same var node = root and loop, but a missing key returns false and nothing is created.
    10. Answer with the flag. After the loop, return node.isEnd.
    11. startsWith repeats the walk once more, with a prefix in place of the word. A missing key returns false, and finishing the loop returns true.

    The solution in Scala

    class TrieNode {
        val children = scala.collection.mutable.Map[Char, TrieNode]()
        var isEnd = false
    }
    
    class Trie {
        val root = new TrieNode()
    
        def insert(word: String): Unit = {
            var node = root
            for (c <- word) {
                if (!node.children.contains(c)) {
                    node.children(c) = new TrieNode()
                }
                node = node.children(c)
            }
            node.isEnd = true
        }
    
        def search(word: String): Boolean = {
            var node = root
            for (c <- word) {
                if (!node.children.contains(c)) {
                    return false
                }
                node = node.children(c)
            }
            return node.isEnd
        }
    
        def startsWith(prefix: String): Boolean = {
            var node = root
            for (c <- prefix) {
                if (!node.children.contains(c)) {
                    return false
                }
                node = node.children(c)
            }
            return true
        }
    }
    

    The Scala details worth a closer look:

    • contains before apply. node.children(c) on a missing key throws a NoSuchElementException ("key not found"). The code tests contains first. The alternatives are get(c), which returns an Option (None for a missing key), and getOrElseUpdate(c, new TrieNode()), which would shorten insert to one line.
    • Assignment syntax on a map. node.children(c) = new TrieNode() is shorthand for node.children.update(c, new TrieNode()). It adds the key or replaces its value.
    • for (c <- word). A String can be looped over as a sequence of Chars, so c is a Char, which matches the map's key type.
    • return inside a for. It leaves the whole method, not only the loop. Scala 3.5 compiles this, prints a warning about non-local returns, and runs the code as expected, because the loop body is a function internally.
    • val and var on a node. node is a var because it moves down the trie, and the loop reassigns it. root is a val because it never changes.
    • new. The lesson writes new TrieNode(). In Scala 3, TrieNode() works too.

    Complexity

    Time: O(L) per operation. Each of the three methods visits at most one node per letter of its argument, and a lookup or an insertion in the map of a node is constant on average.

    Space. The trie holds at most one node per inserted letter, so after inserting words with a total of T letters it has at most T + 1 nodes, counting the root. Words that share a prefix share its nodes: after inserting "apple" and "app" the trie has 6 nodes, and after "car" and "cart" it has 5. search and startsWith use O(1) extra space.

    Edge cases and common mistakes

    • A prefix is not a word. After insert("apple"), search("app") is false. A version that returns true after reaching the node, without checking isEnd, gets this wrong.
    • A word is a prefix of itself. After insert("dog"), startsWith("dog") is true.
    • Longer than anything inserted. After insert("dog"), both startsWith("dogs") and search("dogs") are false: the walk fails at the letter s.
    • Inserting a word twice. The second insert finds every node present and sets the flag again, so nothing changes.
    • Inserting a prefix later. After insert("apple"), insert("app") creates no node. It only sets isEnd on the existing node for "app".
    • Reading a missing key directly. node.children(c) without the contains test throws an exception for a letter that no word uses.
    • The empty prefix. startsWith("") returns true without looking at any letter, even on an empty trie. The lesson's inputs are at least one letter long.

    Testing

    • insert("apple"), then search("apple"), search("app"), startsWith("app") give true, false, true. After insert("app"), search("app") gives true.
    • insert("car"), insert("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.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free