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 that prefix. Words that begin the same way share the same path from the root, so a lookup takes time that depends only on the length of the word asked about, not on how many words are stored.
The class Trie has three methods:
insert(word)addsword.search(word)returnsTrueonly ifwordwas inserted itself.startsWith(prefix)returnsTrueif some inserted word starts withprefix. A word counts as a prefix of itself.
After insert("apple"), search("apple") is True, but search("app") is False: "app" is only the beginning of a longer word. startsWith("app") is True. After insert("app") as well, search("app") becomes True. Inserting the same word twice changes nothing.
Approach: one node per prefix, one flag per word end
The trie is made of TrieNode objects. Each node has a children dictionary that maps a letter to the child node for that letter, and a flag isEnd that says whether an inserted word finishes at this node. The trie keeps one root node, which stands for the empty prefix.
The flag is needed because the path alone can't tell the difference between a word and the beginning of a longer one. After inserting "apple" and then "app", walking down the letters gives these nodes:
a isEnd=False children=['p']
p isEnd=False children=['p']
p isEnd=True children=['l']
l isEnd=False children=['e']
e isEnd=True children=[]
The third node, the one for "app", has isEnd=True only because "app" was inserted. Before that insert it was False, and the path was still there.
All three methods are the same walk from the root, one letter at a time. They differ in what they do when a letter has no child and in what they return at the end:
insertcreates the missing child and finally setsisEnd;searchreturnsFalseat a missing child, and at the end returns the node'sisEnd;startsWithreturnsFalseat a missing child, and at the end returnsTrue, because every node of the trie lies on the path of some inserted word.
Each operation visits one node per letter, so it takes O(L) time for a word of length L.
Step by step
- Give
TrieNodeachildrendict. In__init__,self.children = {}maps a letter to its child. A dictionary finds a child in one step and holds only the letters that some word uses. - Add the
isEndflag, starting asFalse. - Create the root. In
Trie.__init__, setself.roottoTrieNode(). An empty trie is a root with no children. - In
insert, startnodeatself.root. - Loop over each character
cofword. Each letter goes one level deeper. - Create a missing child. If
cis not innode.children, store a newTrieNode()underc. - Move down with
node = node.children[c]. The child exists now, whether it was there before or was just created. - Mark the word's end. After the loop, set
node.isEnd = True. - In
search, start at the root and loop over the letters ofwordin the same way, creating nothing. - Return
Falseat a missing letter. Ifcis not innode.children, nothing inserted continues this way. - Move down to the child.
- Return
node.isEndafter the loop. Reaching the node isn't enough, because the path may belong to a longer word only. - In
startsWith, repeat the walk overprefix, returningFalseat a missing letter. - Return
Trueafter the loop. Every letter of the prefix had a child, so the path exists.
The solution in Python
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isEnd = True
def search(self, word: str) -> bool:
node = self.root
for c in word:
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
def startsWith(self, prefix: str) -> bool:
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True
Python details worth a closer look:
- Dictionary membership.
c not in node.childrenchecks the keys of the dict, in constant time on average. Readingnode.children[c]for a missing key would raiseKeyError, so every read comes after that check or after the insertion. - A fresh dict per node.
self.children = {}runs in__init__, so every node gets its own dictionary. A dict written once in the class body would be shared by all nodes and mix every word together. - Iterating a string.
for c in wordgives one-character strings, which serve directly as dict keys. - The walk modifies a local name.
node = node.children[c]only rebinds the variablenode.self.rootstill points at the root afterwards. - Return types.
searchreturnsnode.isEnddirectly, which is already abool.
Complexity
Time: O(L) per operation, where L is the length of the word or prefix. Each letter costs one dictionary lookup, plus one node creation in insert. With words of up to 30 letters, each call does at most 30 steps.
Space: O(total letters inserted). At worst every inserted letter creates a new node. Words that share a prefix share its nodes, so the real count is often smaller. Searching and startsWith use no extra space.
Edge cases and common mistakes
- A prefix that was never inserted as a word. After inserting
"car"and"cart",startsWith("ca")isTrueandsearch("ca")isFalse. - No word continues the letters.
startsWith("cat")isFalsefor the same two words, because the node for"ca"has onlyras a child. - Inserting the same word twice. After inserting
"dog"two times,search("dog")andstartsWith("dog")areTrue, whilesearch("do"),startsWith("dogs")andsearch("dogs")areFalse. The second insert finds every node already in place and sets the flag again. - A word longer than anything inserted.
search("dogs")fails at the missingschild. - Forgetting
isEndinsearch. ReturningTrueafter the loop would makesearch("app")true after inserting only"apple". - Creating nodes while searching. A search or
startsWiththat adds missing children, such as withsetdefault, makes later calls return wrong answers, because the trie then holds prefixes nobody inserted. - An empty trie. Before any insert,
startsWith("a")andsearch("a")are bothFalse, since the root has no children.
Testing
- Insert
"apple", thensearch("apple"),search("app"),startsWith("app"), insert"app",search("app"):True,False,True,True. - Insert
"car"and"cart", thenstartsWith("ca"),search("ca"),startsWith("cat"),search("cart"):True,False,False,True. - Insert
"dog"twice, thensearch("dog"),startsWith("dog"),search("do"),startsWith("dogs"),search("dogs"):True,True,False,False,False. - On an empty trie,
startsWith("a")andsearch("a"):False,False.
