Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 15  /  TRIE

The Word Tree.

Store a whole dictionary so that every shared prefix is shared just once. Insert words letter by letter, watch CAT and CAR grow the same trunk, then answer "is this a word?" or "any word start with this?" in one walk down.

THE GIST · 20 SECONDS

A trie (prefix tree) stores strings in a tree where each edge is a letter and each path from the root spells a prefix. Words that share a prefix share a path; a flag marks where a real word ends. Insert walks down creating missing nodes; search walks down and checks the end flag; startsWith just checks the path exists. Every op is O(length).

  • Nodeone letter on a path
  • Shared prefixone path, many words
  • End flaga real word stops here
  • O(L)cost = word length

Hit Step to insert the next letter — or Play and watch the words grow into a tree, then search it.

UNDER THE HOOD

What you just played, written down

A trie trades memory for speed: it factors out shared prefixes into shared paths, so a lookup costs only the length of the word — never the size of the dictionary.

How a trie thinks — four moves

  1. The root is empty. Every path starts there; each step down consumes one character of a word.
  2. Insert: walk & grow. For each letter, follow the child if it exists or create it. Mark the final node is_end = true.
  3. Share prefixes for free. CAT and CAR both walk C→A, so that prefix exists once. Only the diverging letters add nodes.
  4. Search vs startsWith. Both walk the letters. search also requires the end flag; startsWith only needs the path to exist.
WHY THE END FLAG MATTERS

Inserting CAR and CARD means the node after CAR is a real word and a prefix of a longer one. The is_end flag is how the trie tells "this is a stored word" apart from "this is only a prefix so far."

The whole thing in code

class Trie:
    def __init__(self):
        self.kids = {}          # letter -> Trie node
        self.end = False

    def insert(self, word):
        node = self
        for ch in word:
            if ch not in node.kids:
                node.kids[ch] = Trie()   # grow
            node = node.kids[ch]
        node.end = True          # a word ends here

    def search(self, word):
        node = self._walk(word)
        return node is not None and node.end

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

    def _walk(self, s):
        node = self
        for ch in s:
            if ch not in node.kids: return None
            node = node.kids[ch]
        return node
TIMEO(L)per insert / search
SPACEO(Σ·N)chars × alphabet
WHY NOT JUST A HASH SET?

A hash set answers "is this exact word here?" fast — but it can't answer "which words start with 'car'?" without scanning everything. The trie makes prefix queries and autocomplete natural and cheap.

⚠ Memory can balloon

A node per character per branch is a lot of pointers. Compressed tries (radix trees) merge single-child chains, and array-vs-map children trade speed for space depending on the alphabet.

↔ Its relatives

Radix / Patricia tries compress chains; suffix tries/trees index every suffix of one string; Aho-Corasick adds KMP-style failure links for multi-pattern search.

★ Where it's used

Autocomplete & type-ahead, spell-checkers, IP routing (longest-prefix match), T9 predictive text, and dictionary compression.

The picture: four words, one trunk

·CDATRDOG CATCARCARDDOG 8 nodes for13 letters typed
The finished trie for CAT, CAR, CARD and DOG. The root (·) holds no letter. Green nodes carry the end flag. CAT, CAR and CARD all start from the single C → A path, and R is both the end of CAR and an interior node on the way to CARD, which is why a flag is needed at all.

Worked example, step by step

Insert CAT, CAR, CARD, DOG into an empty trie, then run six queries. “Steps” counts the edges followed (or attempted). Every figure comes from running the code on this input.

OperationInputStepsNew nodes / resultTotal nodes / reason
insert CATCAT333
insert CARCAR314
insert CARDCARD415
insert DOGDOG338
search CARCAR3trueend flag set
search CACA2falsepath exists, flag off
startsWith CACA2truepath exists
search CARDSCARDS5falsepath missing
startsWith DODO2truepath exists
search DOGDOG3trueend flag set

Four words and 13 letters produced 8 nodes. CAR cost one new node because C and A already existed; CARD cost one more. Two queries show why the end flag exists: search CA is false although startsWith CA is true, since the path is there but no word ends on it. search CARDS stops after 5 steps, the failed attempt at the fifth letter, and the cost of every query depends on the word's length and never on how many words are stored.

Complexity and trade-offs

CaseTimeSpaceWhy
Trie (map children)O(L) insert, search, prefixO(total letters) worst caseCost is the length of the word, whatever the dictionary size. Children in a map or dict.
Trie (array children)O(L)O(nodes × alphabet)No hashing per step, but every node reserves a slot per letter, used or not.
Hash set of wordsO(L) to hash, then O(1)O(total letters)Exact lookup is as fast, but a prefix query must scan every word.
Sorted array + binary searchO(L log n)O(total letters)Prefix queries become a range, but inserts cost O(n) shifts.
Compressed trie (radix tree)O(L)O(words) nodesMerges single-child chains into one edge, so node count tracks words, not letters.

Sharing prefixes saves nodes only when words overlap. Take every three-letter string over a–z (17,576 words, 52,728 letters): the trie needs 18,278 nodes, 2.9 letters per node. Take 10,000 random eight-letter strings (80,000 letters) from a fixed generator: 58,237 nodes, almost no sharing, 1.37 letters per node, and each node still carries a child table. An array-children trie would reserve 1,514,162 slots for those 10,000 words. For the prefix ab in the three-letter corpus the trie follows 2 edges and then visits 26 nodes below it to list 26 words; a hash set would test all 17,576.

Common mistakes

  • Returning true for any existing path

    A search that only checks the path exists is really startsWith. After inserting only CARD, the buggy version answers search("CAR") = true. The fix is the final return node.end.

  • Sharing one children dict between all nodes

    In Python, declaring kids = {} in the class body instead of in __init__ gives every node the same dict. After inserting only "CAT", search("CT") returns True (verified by running it), because all nodes read and write one common dict.

  • Indexing an array of 26 with unchecked input

    With kids = [None] * 26 and index ord(c) - 97, inserting "Cat" computes index −30 for the capital C and raises IndexError in Python; an apostrophe in "c'a" fails the same way. Normalise case and reject or map other characters before indexing.

  • Deleting by cutting the node out

    Removing the node for CAR from its parent also removes CARD below it. After doing that in the example, search("CARD") = false and search("CAR") = false, while search("CAT") = true. To delete a word, clear its end flag, then prune only nodes that have no children and no flag.

  • Inserting recursively with long words

    A recursive insert(word[1:]) makes one call per letter. In Python, inserting a 2,000-letter string raises RecursionError under the default recursion limit. A loop uses constant stack.

SOLVE IT YOURSELF

Solve it: build a Trie

This one is yours to write — in Python or TypeScript, running for real in your browser. Implement insert, search, and startsWith. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement a Trie class with insert(word), search(word) (exact word present?), and starts_with(prefix) (any word begins with this prefix?). Each node maps a character to a child node and carries an end-of-word flag.

HINTS — 4 IDEAS
  1. Represent each node as a dict of char → node plus a boolean end.
  2. insert: walk the word, creating missing children, then mark the last node end = True.
  3. search: walk the word; return True only if you finish and the final node's end is set.
  4. starts_with: walk the prefix; return True if the whole path exists (ignore the end flag).
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. Why do CAT and CAR only add one extra node each after sharing C-A?

    Answer: Because words that share a prefix share the same path in the trie — A trie factors out shared prefixes into a shared path. CAT and CAR walk the same C→A nodes, then diverge — only the differing letters T and R create new nodes.

  2. search("car") returns True but search("ca") returns False. Why?

    Answer: "ca" exists as a path but its node has no end-of-word flag — The path c→a exists (it is a prefix of car and card), but no word "ca" was inserted, so that node’s end flag is false. search requires the end flag; startsWith would return True.

  3. What is the time complexity of searching a trie for a word of length L?

    Answer: O(L), independent of how many words are stored — You follow one child per character, so a search touches exactly L nodes regardless of the dictionary size — O(L).

FAQ

Tries, answered

What is a trie?

A prefix tree: a tree where each edge is a character and each path from the root spells a prefix. Words that share a prefix share a path, and an end-of-word flag marks where a real word stops. It's the classic structure behind autocomplete.

How does searching work?

Start at the root and follow the child edge for each character. If a needed child is missing, the word isn't there. If you consume all characters and the final node's end flag is set, the word is stored.

search vs startsWith?

Both walk the characters. search also requires the final node's end flag (the exact word was inserted); startsWith only needs the path to exist (some word begins with that prefix).

What's the complexity?

Insert, search, and startsWith are all O(L) — the length of the word or prefix — independent of how many words are stored. Space is O(total characters × alphabet), which can be large.

Where are tries used?

Autocomplete and type-ahead, spell-checkers, IP routing (longest-prefix match), T9 predictive text, and multi-pattern search via Aho-Corasick.

RESULT

—

Next → hang KMP-style failure links off every trie node and you can match many patterns in one text pass — that's the Aho-Corasick automaton.

Finished this one? 0 / 99 Algorithms done
NextSuffix Array: Suffixes, Sorted Next on the “Indexing the text instead” ladder · rung 2 of 2

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms