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) -> Boolreturnstrueonly if that exact word was inserted before.startsWith(_ prefix: String) -> Boolreturnstrueif 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
- Give
TrieNodeits children. Declarevar children: [Character: TrieNode] = [:], an empty dictionary from each next letter to the child node. Aforloop over aStringproducesCharactervalues, so those are the keys. - Add the word-end flag:
var isEnd = false, which becomestrueon the node where an inserted word ends. - Give
Triea root:let root = TrieNode(). It always refers to the same node, although the node itself changes, soletis enough. - In
insert, start at the root withvar node = root. - Loop over the characters of
word. Each letter takes the walk one level down. - Create a missing child. If
node.children[c]isnil, store a newTrieNode()there. A dictionary lookup for a missing key givesnil. - Move down with
node = node.children[c]!. The lookup returns an optional, and the!is safe because theifabove made sure the child exists. - 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. - In
search, start at the root and loop over the characters again. - Return
falsewhen a child is missing. No inserted word continues that way. - Move down the same way as in
insert. - Return
node.isEnd. Reaching the node isn't enough: after inserting "apple", the path for "app" exists, but no word ends there. - In
startsWith, walk the prefix with the same loop, returningfalseon a missing child and moving down otherwise. - Return
trueafter 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 typeTrieNode?:nilfor a missing key. That is why the code compares it withniland unwraps it with!. Applying!to a missing key crashes the program, so thenilcheck always comes first. - Classes are reference types.
var node = rootmakesnoderefer to the sameTrieNodeobject asroot, not a copy. Writing tonode.childrenchanges the trie itself. The variablenodeis avarbecause it is reassigned as the walk goes down;rootis aletbecause it never is, even though the node it refers to changes. - Looping over a
StringgivesCharactervalues. They match the dictionary's key type directly, so no conversion is needed. ACharacteris 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] = [:]andvar isEnd = falsehave initial values, soTrieNode()works with no custom initializer, and so doesTrie(). - Methods on a class change its properties. No
mutatingkeyword is needed, becauseTrieNodeandTrieare 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")andsearch("cart")are bothtrue: 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")istrueandsearch("ca")isfalse. - Letters that lead nowhere.
startsWith("cat")isfalsethere, 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")andstartsWith("dog")aretrue, whilesearch("do"),startsWith("dogs")andsearch("dogs")arefalse. - Returning
trueat the end ofsearch. That turns it intostartsWith. The flag is the only difference between the two. - Forgetting the flag in
insert. Withoutnode.isEnd = true, nosearchever succeeds. - Forcing the unwrap before checking. Writing
node = node.children[c]!insearchwithout thenilcheck crashes on any word that isn't in the trie. - An empty trie. A fresh
Trie()answersfalseto bothsearch("a")andstartsWith("a").
Testing
insert("apple"), thensearch("apple"),search("app"),startsWith("app")givetrue,false,true. Afterinsert("app"),search("app")givestrue.insert("car"),insert("cart"), thenstartsWith("ca"),search("ca"),startsWith("cat"),search("cart")givetrue,false,false,true.insert("dog")twice, thensearch("dog"),startsWith("dog"),search("do"),startsWith("dogs"),search("dogs")givetrue,true,false,false,false.
