Advanced · Prefix tree · Strings

Trie Visualizer

What is Trie

Insert a list of lowercase words into a trie. Then answer queries. S word returns 1 when that exact word was inserted. P word returns 1 when some inserted word starts with that prefix.

Example. Insert app, apple, and apt. S app and S apple are words. P ap is a prefix. S ape is not a stored word.

Words: app apple apt
Queries: S app, S apple, P ap, S ape
Output: 1 1 1 0

Constraints. Up to 1000 words and 1000 queries, each of length at most 20. This picture draws 4 words, 4 queries, and 6 letters each.

Approach

Insert Start at the root. For each letter, follow the existing edge or create it. Mark the node of the last letter as the end of a word.
Query Walk the letters again. A missing edge means both search and prefix fail. If the walk finishes, a prefix query succeeds. An exact search also needs the end-of-word mark.

Words that share a beginning, such as app and apple, share the same nodes. The brighter nodes in the picture are word ends.

Interactive solution

Prefix tree
class Trie:
def insert(self, word):
node = root
for ch in word:
node = node.child(ch)
node.end = True
def search(self, word):
node = walk(word)
return node is not None and node.end
def starts_with(self, prefix):
return walk(prefix) is not None
Step 0/0 Answer —

The finished structure is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
Insert / queryO(L)L is the length of that word. Each letter is one edge.
SpaceO(total letters)Shared prefixes store each edge once.

Implementation

def insert(self, word):
    node = self.root
    for ch in word:
        node = node.setdefault(ch, {})
    node["#"] = True

def search(self, word):
    node = self._walk(word)
    return node is not None and node.get("#", False)

def starts_with(self, prefix):
    return self._walk(prefix) is not None