Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Swift: 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

    SWIFT · TRIES

    Implement Trie Prefix Tree in Swift, explained

    Problem overview

    A trie, or prefix tree, stores words letter by letter. 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. You implement the class Trie with three methods:

    • insert(_ word: String) adds a word.
    • search(_ word: String) -> Bool returns true only if that exact word was inserted before.
    • startsWith(_ prefix: String) -> Bool returns true if some inserted word starts with the prefix. A word counts as a prefix of itself.

    After insert("apple"), search("apple") is true, but search("app") is false, because "app" is only the beginning of a word. startsWith("app") is true. After insert("app"), search("app") becomes true too.

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

    Approach: one node per prefix

    A list of words would make search compare the query with every word, so the time would depend on how many words are stored. A trie makes the time depend only on the query. To look up a word, start at the root, which stands for the empty prefix, and follow one child per letter. If a child is missing at any point, no inserted word continues that way.

    Each node needs two things: a map from the next letter to the child node, and a flag that says whether an inserted word ends at this node. The flag matters because prefixes share nodes with words. Inserting "apple" creates nodes for "a", "ap", "app", "appl" and "apple", and only the flag tells which of them end a word. Insert "app" afterwards and the node for "app" gets the flag, with no new nodes.

    After inserting "apple", "app" and "apt", the trie looks like this, as read from the nodes:

    root          children: a                isEnd: false
    "a"           children: p                isEnd: false
    "ap"          children: p, t             isEnd: false
    "app"         children: l                isEnd: true
    "apt"         children: (none)           isEnd: true
    

    The three operations are the same walk with a different ending. insert creates missing children and sets the flag on the last node. search returns false on a missing child and the last node's flag otherwise. startsWith returns false on a missing child and true if it gets to the end of the prefix, because every node in the trie lies on the path of some inserted word.

    Step by step

    1. Give TrieNode its children. Declare var children: [Character: TrieNode] = [:], an empty dictionary from each next letter to the child node. A for loop over a String produces Character values, so those are the keys.
    2. Add the word-end flag: var isEnd = false, which becomes true on the node where an inserted word ends.
    3. Give Trie a root: let root = TrieNode(). It always refers to the same node, although the node itself changes, so let is enough.
    4. In insert, start at the root with var node = root.
    5. Loop over the characters of word. Each letter takes the walk one level down.
    6. Create a missing child. If node.children[c] is nil, store a new TrieNode() there. A dictionary lookup for a missing key gives nil.
    7. Move down with node = node.children[c]!. The lookup returns an optional, and the ! is safe because the if above made sure the child exists.
    8. Mark the end. After the loop, set node.isEnd = true. This is what makes the word count as inserted rather than as the start of a longer word.
    9. In search, start at the root and loop over the characters again.
    10. Return false when a child is missing. No inserted word continues that way.
    11. Move down the same way as in insert.
    12. Return node.isEnd. Reaching the node isn't enough: after inserting "apple", the path for "app" exists, but no word ends there.
    13. In startsWith, walk the prefix with the same loop, returning false on a missing child and moving down otherwise.
    14. Return true after the loop. Every letter of the prefix had a child, so the path exists.

    The solution in Swift

    class TrieNode {
        var children: [Character: TrieNode] = [:]
        var isEnd = false
    }
    
    class Trie {
        let root = TrieNode()
    
        func insert(_ word: String) {
            var node = root
            for c in word {
                if node.children[c] == nil {
                    node.children[c] = TrieNode()
                }
                node = node.children[c]!
            }
            node.isEnd = true
        }
    
        func search(_ word: String) -> Bool {
            var node = root
            for c in word {
                if node.children[c] == nil {
                    return false
                }
                node = node.children[c]!
            }
            return node.isEnd
        }
    
        func startsWith(_ prefix: String) -> Bool {
            var node = root
            for c in prefix {
                if node.children[c] == nil {
                    return false
                }
                node = node.children[c]!
            }
            return true
        }
    }
    

    The Swift details worth a closer look:

    • Dictionary lookups are optionals. node.children[c] has the type TrieNode?: nil for a missing key. That is why the code compares it with nil and unwraps it with !. Applying ! to a missing key crashes the program, so the nil check always comes first.
    • Classes are reference types. var node = root makes node refer to the same TrieNode object as root, not a copy. Writing to node.children changes the trie itself. The variable node is a var because it is reassigned as the walk goes down; root is a let because it never is, even though the node it refers to changes.
    • Looping over a String gives Character values. They match the dictionary's key type directly, so no conversion is needed. A Character is one user-perceived character, so for the lowercase letters of this lesson it is one per letter.
    • Default values for properties. var children: [Character: TrieNode] = [:] and var isEnd = false have initial values, so TrieNode() works with no custom initializer, and so does Trie().
    • Methods on a class change its properties. No mutating keyword is needed, because TrieNode and Trie are classes.

    Complexity

    Time: O(L) per operation. Each letter costs one dictionary lookup and, in insert, possibly one node creation, and a dictionary lookup takes constant time on average. The work does not depend on how many words are stored.

    Space: O(N) in the total number of letters over all inserted words, in the worst case, when no two words share a prefix. Shared prefixes share nodes, so many similar words take less. search and startsWith use only a constant amount of extra space.

    Edge cases and common mistakes

    • A word that is a prefix of another. After inserting "car" and "cart", search("car") and search("cart") are both true: the node for "car" has its own flag and one child.
    • A prefix that was never inserted as a word. After inserting "car" and "cart", startsWith("ca") is true and search("ca") is false.
    • Letters that lead nowhere. startsWith("cat") is false there, because the node for "ca" has no child for "t".
    • Inserting twice. After insert("dog") twice, nothing changes: the nodes exist and the flag is set again. search("dog") and startsWith("dog") are true, while search("do"), startsWith("dogs") and search("dogs") are false.
    • Returning true at the end of search. That turns it into startsWith. The flag is the only difference between the two.
    • Forgetting the flag in insert. Without node.isEnd = true, no search ever succeeds.
    • Forcing the unwrap before checking. Writing node = node.children[c]! in search without the nil check crashes on any word that isn't in the trie.
    • An empty trie. A fresh Trie() answers false to both search("a") and startsWith("a").

    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 Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free