Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Kotlin: O(L) Insert and Search

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

    KOTLIN · TRIES

    Implement Trie Prefix Tree in Kotlin, 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. Words that begin the same way share the same path from the root.

    The class Trie has three methods:

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

    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.

    The statement asks each operation to run in O(L) time, where L is the length of the word or prefix.

    Approach

    A list of words would need a scan of every word for each question. A hash set answers search quickly but can't answer startsWith without checking every word. A trie answers both by walking down from the root one letter at a time, so the time depends only on the length of the word asked about, not on how many words are stored.

    Each node holds two things: a map from a letter to the child node for that letter, and a flag saying whether an inserted word ends at this node. The flag matters because after inserting "apple" the nodes for "app" and "apple" both exist, and only the flag tells which of them ends a word. That one flag is the whole difference between search and startsWith.

    Step by step

    1. Write TrieNode. Give it val children, a HashMap<Char, TrieNode>() that maps each next letter to its child, and var isEnd, set to false. The map is in a val, so it is always the same map, although it can still grow. The flag is a var because it changes later.
    2. Give Trie a root: val root = TrieNode(). The root stands for the empty prefix, so an empty trie is a root with no children.
    3. In insert, start at the root with var node = root and loop over the letters of word.
    4. Create missing paths. If a letter is not in node.children (c !in node.children), store a new TrieNode() under it.
    5. Move down with node = node.children[c]!!. The child exists now, whether it was there before or was just created.
    6. Mark the end. After the loop, node.isEnd = true turns the path into an inserted word.
    7. In search, follow the same walk but create nothing. If a letter has no child, return false. After the loop return node.isEnd: reaching the node is not enough, because the path for "app" exists after inserting "apple".
    8. In startsWith, do the same walk and return true after the loop. Every node of the trie lies on the path of some inserted word, so if every letter of the prefix had a child, some word starts with it.

    The solution in Kotlin

    class TrieNode {
        val children = HashMap<Char, TrieNode>()
        var isEnd = false
    }
    
    class Trie {
        val root = TrieNode()
    
        fun insert(word: String) {
            var node = root
            for (c in word) {
                if (c !in node.children) {
                    node.children[c] = TrieNode()
                }
                node = node.children[c]!!
            }
            node.isEnd = true
        }
    
        fun search(word: String): Boolean {
            var node = root
            for (c in word) {
                if (c !in node.children) {
                    return false
                }
                node = node.children[c]!!
            }
            return node.isEnd
        }
    
        fun startsWith(prefix: String): Boolean {
            var node = root
            for (c in prefix) {
                if (c !in node.children) {
                    return false
                }
                node = node.children[c]!!
            }
            return true
        }
    }
    

    Some Kotlin details in this code:

    • HashMap is available in Kotlin without an import, and HashMap<Char, TrieNode>() creates an empty one.
    • c !in node.children checks the map's keys, and in is the positive form. It reads better than containsKey.
    • node.children[c] = TrieNode() stores a value under a key with index syntax.
    • Looking up a key, node.children[c], has the type TrieNode?, because the key might be missing: for an empty map, map['x'] gives null. The !! says it is not null here, and the if above made sure of that.

    Following the examples

    For insert("car"), insert("cart"), then startsWith("ca"), search("ca"), startsWith("cat") and search("cart"), the results are:

    [true, false, false, true]
    

    "ca" is a path in the trie, so startsWith says true, but no word ends there, so search says false. There is no t child under "ca", so "cat" fails at its third letter.

    Inserting "dog" twice changes nothing: the second walk finds every node already there and sets isEnd to true again. The trie then has a chain of three nodes below the root.

    Complexity

    Time: O(L) per operation, where L is the length of the word or prefix. Each letter costs one hash map lookup or insertion, which takes constant time on average.

    Space: O(N), where N is the total number of letters in all inserted words, since each letter creates at most one node. Shared prefixes are stored once, so the real figure is often smaller.

    Edge cases and common mistakes

    • A word that is a prefix of another. With "app" and "apple" both inserted, both search calls say true. The isEnd flag on the node for "app" is what allows it.
    • A prefix that is not a word. After "apple" only, search("app") is false and startsWith("app") is true.
    • Inserting the same word twice. It is harmless.
    • A prefix longer than any word. After "dog", both startsWith("dogs") and search("dogs") are false: the walk fails at the fourth letter.
    • Returning true from search without the flag. That turns search into startsWith.
    • Creating nodes while searching. search and startsWith must not add nodes, or a failed lookup would change the answers of later ones.

    Testing

    insert("apple") search("apple") search("app") startsWith("app") insert("app") search("app")  -> true false true true
    insert("car") insert("cart") startsWith("ca") search("ca") startsWith("cat") search("cart")  -> true false false true
    insert("dog") insert("dog") search("dog") startsWith("dog") search("do") startsWith("dogs") search("dogs")  -> true true false false false
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free