A hash set is perfect for asking “is this exact word stored?”. It stops being enough when the question becomes “is anything stored that starts with these letters?”.

A trie handles that second question. It spells every stored word as a path that starts from one shared root. Words that begin the same way share the same nodes for that shared beginning. So a prefix query costs one step per character of the prefix, no matter how many words you’ve stored.

This post builds directly on Trees. Trees unlocks three topics, and this is one of them, next to Heap / Priority Queue and Backtracking. Nothing later in the series depends on it, so you can treat it as a leaf of the series.

How to use this post: the method. The checkpoints don’t show answers on the page. Work each one out yourself first, then open the linked chat to have your answer checked.

Trie

Foundation

Think of the thumb tabs on a paper dictionary. To find “card” you don’t scan every word. You jump to C, then to the CA section, then to CAR. At each step, every word that doesn’t start with what you’ve read so far is already out of view.

A trie makes that literal:

  • The root stands for the empty string.
  • Each edge adds one character.
  • Follow the characters of some string s from the root, and the node you land on is s. It represents exactly one prefix, s, and nothing else.
  • Everything below that node belongs to the stored words that start with s.

Here is the picture to keep in your head. A trie is the set of all prefixes of all stored words. Each distinct prefix is stored once, as a node, and each node points to the prefixes that are one character longer.

There’s a catch. In this structure, a whole word and a prefix look the same: “car” is a word, but it’s also a prefix of “card”. So each node also carries a flag or a counter that says “a stored word ends exactly here”.

What does it solve? Two kinds of problem:

  • Prefix questions. Does any word start with p? How many do? List them. A trie answers these in O(length of p) time instead of O(number of words).
  • Shared-prefix walks. Many words get matched against the same input, one character at a time. Words with a common prefix share the work for that prefix, so it’s only done once.

Mechanics

I don’t want to spoil the problems in this topic’s list. So I’ll teach the trie through an API that none of them uses: a word counter. It supports four operations:

  • insert(word). Duplicates are allowed.
  • count_words(word): how many times exactly this word was inserted.
  • count_prefix(prefix): how many inserted words start with prefix.
  • completions(prefix): every inserted word that starts with prefix, in sorted order.

Each node holds three things:

  • children: a dict that maps one character to the next node.
  • pass_count: how many inserted words run through this node.
  • end_count: how many inserted words end exactly here.

Worked example. We insert these words, in this order: cat, car, card, care, dog. That’s 5 words and 3 + 3 + 4 + 4 + 3 = 17 characters.

Insert walks down, creating only what is missing. Start at the root. For each character of the word:

  1. If the current node has no child for that character, create one.
  2. Step into the child, and add 1 to its pass_count.

After the last character, add 1 to that node’s end_count. Here’s what happens on the example:

  • cat: c new, a new, t new. The trie now has 4 nodes (root plus 3).
  • car: c reused, a reused, r new. 5 nodes.
  • card: c, a, r reused, d new. 6 nodes.
  • care: c, a, r reused, e new. 7 nodes.
  • dog: d new, o new, g new. 10 nodes.

17 characters went in, but only 9 non-root nodes came out. That’s because four words shared the path for “ca”, and three of them also shared “car”.

Why is it safe to reuse a node? Because a node represents one prefix and nothing else. The node you reach by following c then a is the “ca” node, whichever word led you there. So cat and card both belong under it. If you created a second “ca” node, the words starting with “ca” would be split across two places, and every prefix count would come out wrong.

Why the root gets counted too. Insert also adds 1 to root.pass_count. Every word starts with the empty prefix “”, so root.pass_count ends up as the total number of words (5 here). That makes count_prefix(“”) correct without any special case.

A lookup is a walk that may fall off. count_words and count_prefix share one helper. It walks down from the root, following the query’s characters one by one. It returns the node it lands on, or None the moment a character has no child.

Take the walk for “car”. It visits c (pass 4, end 0), then a (pass 4, end 0), then r (pass 3, end 1). It lands on the r node, so:

  • count_prefix(“car”) = 3, for car, card and care.
  • count_words(“car”) = 1.

Now the walk for “cab”. It visits c and a, then finds no b child, so it returns None. Both counts are 0.

Why is it safe to stop at the first missing character? Suppose some inserted word did start with “cab”. Then insert would have created exactly that b node under “ca”. The node isn’t there, so no such word was ever inserted, and there’s nothing further down to find.

The key invariant. An invariant is a fact that stays true no matter what sequence of operations you run. Here it has three parts. After any sequence of inserts, for any prefix p:

  • The node for p exists if and only if some inserted word starts with p.
  • Its pass_count equals the number of inserted words that start with p, counting duplicates.
  • Its end_count equals the number of inserted words that are exactly p.

Every operation above just reads one of these facts off the right node.

Telling a word from a prefix. The “ca” node exists and has pass_count 4. Yet count_words(“ca”) is 0, because its end_count is 0. A node existing only means “some word starts like this”. It never means “this is a word”. Mixing those two up is the most common trie bug I know of, and it’s the reason end_count (or an is_end flag) exists.

Listing completions is a DFS below the walk. DFS, or depth-first search, means you go all the way down one branch before backing up to try the next. First, walk to the prefix node. From there, run a DFS over its children, keeping the characters of the current path in a list:

  • Append a character before you recurse into a child.
  • Pop it after you come back.
  • Whenever the node you’re on has end_count > 0, the current path spells a stored word.

For “ca”, visiting children in sorted order gives car, card, care, cat. This is the same DFS as in the Trees post, with one difference. A binary tree node has at most two children, but a trie node can have up to one child per letter of the alphabet.

Diagram

The trie after inserting cat, car, card, care, dogpass counts the words passing through a node, end the words ending there. root (pass 5, end 0) has children c and d. c (pass 4, end 0) leads by a to ca (pass 4, end 0). ca leads by r to car (pass 3, end 1) and by t to cat (pass 1, end 1). car leads by d to card (pass 1, end 1) and by e to care (pass 1, end 1). d (pass 1, end 0) leads by o to do (pass 1, end 0), which leads by g to dog (pass 1, end 1). Nodes where a word ends are green.rootpass 5 · end 0cpass 4 · end 0dpass 1 · end 0capass 4 · end 0dopass 1 · end 0carpass 3 · end 1catpass 1 · end 1dogpass 1 · end 1cardpass 1 · end 1carepass 1 · end 1cdaortgdeinserted:cat, car, card, care, dogpass = words through hereend = words ending heregreen = a word ends hereblue = the edge’s character
Walking the trie for "car" and for "cab"Query car: step 0 root (pass 5, end 0), step 1 c (pass 4, end 0), step 2 ca (pass 4, end 0), step 3 car (pass 3, end 1): landed, prefix count 3, word count 1. Query cab: steps 0 to 2 are the same, step 3 finds no b child under ca, whose children are only r and t: fell off, prefix count 0, word count 0.query "car"step 0rootpass 5 · end 0step 1cpass 4 · end 0step 2capass 4 · end 0step 3carpass 3 · end 1carlanded: prefix count 3, word count 1query "cab"step 0rootpass 5 · end 0step 1cpass 4 · end 0step 2capass 4 · end 0step 3no bcabca has children r and t onlyfell off: prefix count 0, word count 0

Implementation

class TrieNode:
    __slots__ = ("children", "pass_count", "end_count")

    def __init__(self):
        self.children = {}      # char -> TrieNode, only for characters that actually occur
        self.pass_count = 0     # number of inserted words whose prefix path runs through this node
        self.end_count = 0      # number of inserted words that end exactly at this node


class WordCounter:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        # Every word has the empty prefix, so root.pass_count ends up equal to the
        # total number of inserts (5 after cat, car, card, care, dog).
        node.pass_count += 1
        for ch in word:
            if ch not in node.children:
                # No inserted word has had this prefix yet, so create its node.
                # Example: inserting "card" creates only the d node; c, a, r already exist.
                node.children[ch] = TrieNode()
            node = node.children[ch]
            node.pass_count += 1
        # node is now the node for the full word; count it as a word, not only a prefix.
        node.end_count += 1

    def _walk(self, prefix):
        """Return the node for prefix, or None if no inserted word starts with prefix."""
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)   # .get never creates a node, so lookups can't grow the trie
            if node is None:
                # Example: for "cab", the "ca" node has children {'t', 'r'} and no 'b',
                # so no inserted word starts with "cab" and nothing deeper can exist.
                return None
        return node

    def count_words(self, word):
        node = self._walk(word)
        # A node that exists but has end_count 0 is only a prefix: "ca" -> 0.
        return 0 if node is None else node.end_count

    def count_prefix(self, prefix):
        node = self._walk(prefix)
        # pass_count was maintained during insert, so this is O(len(prefix)) with no subtree scan:
        # "car" -> 3 (car, card, care), "" -> 5, "x" -> 0.
        return 0 if node is None else node.pass_count

    def completions(self, prefix):
        start = self._walk(prefix)
        if start is None:
            return []
        out = []
        path = list(prefix)                # characters of the prefix the current node represents

        def dfs(node):
            if node.end_count:
                # Repeat the word once per insert so duplicates are reported, e.g. "a" inserted twice.
                out.extend(["".join(path)] * node.end_count)
            # sorted() gives lexicographic output; plain dict order would follow first insertion,
            # which yields cat before car for prefix "ca" in this example.
            for ch in sorted(node.children):
                path.append(ch)            # path now spells the child's prefix
                dfs(node.children[ch])
                path.pop()                 # restore path to this node's prefix before the next child

        dfs(start)
        return out


wc = WordCounter()
for w in ["cat", "car", "card", "care", "dog"]:
    wc.insert(w)

print(wc.count_words("car"), wc.count_words("ca"), wc.count_words("cars"))   # 1 0 0
print(wc.count_prefix("car"), wc.count_prefix("ca"), wc.count_prefix(""))   # 3 4 5
print(wc.completions("car"))   # ['car', 'card', 'care']
print(wc.completions("ca"))    # ['car', 'card', 'care', 'cat']
print(wc.completions("z"))     # []

I ran this on the worked example, and it printed the values shown in the comments. I checked some edge cases the same way:

  • An empty WordCounter gives count_prefix(“”) = 0 and completions(“”) = [].
  • After inserting “”, “a”, “a”, you get count_words(“”) = 1, count_words(“a”) = 2, count_prefix(“”) = 3, and completions(“”) = [’’, ‘a’, ‘a’].

Two claims in the code come from memory rather than from working them out here:

  • dict.get returns None for a missing key, and it doesn’t insert that key.
  • Python dicts iterate in insertion order (guaranteed since 3.7). I did confirm this one on the example: iterating the “ca” node’s children without sorted() gives cat, car, card, care.

Complexity. First, some names:

  • L is the length of the word or prefix passed in.
  • S is the total number of characters inserted, across all words.
  • K is the number of nodes in the subtree under the prefix node.
  • σ is the alphabet size (how many different characters can appear).

With those:

  • insert, count_words, count_prefix: O(L) time. Each character costs one dict lookup, and a dict lookup is O(1) on average (from memory: Python dict average case).
  • completions: O(L + K·σ log σ + T) time, where T is the total length of the returned words. The σ log σ part is the sort at each node. For lowercase letters σ = 26, which is a constant, so in practice this is O(L + K + T).
  • Space: at most S + 1 nodes. That’s one node per inserted character, plus the root. Shared prefixes make it smaller in practice: here 17 characters gave only 10 nodes. If each node uses a fixed 26-slot array instead of a dict, multiply that by σ.

Recognition

These are the signals that a trie is in play:

  • Prefix questions. Look for phrases like “starts with”, “autocomplete”, “all words beginning with”, “is any stored word a prefix of this”, or “longest common prefix of a set”.
  • Many words against one input, character by character. You have a dictionary of words and a single text, board or stream, and you scan that input one character at a time. The trie lets the scan give up on a path as soon as the characters so far aren’t a prefix of any word. It also shares that work across every word with the same prefix.
  • Queries that aren’t exact matches. Sometimes one query character can match more than one stored character. A hash set then forces you to list out every candidate string. A trie lets you branch only into children that actually exist.
  • A design problem with insert plus some kind of search over strings. This is especially likely when the constraints give a small alphabet (often lowercase a-z) and short words.

Here is where those signals show up in this topic’s list. Implement Trie Prefix Tree names the structure outright, and it asks prefix questions. Design Add And Search Words Data Structure stores words and asks queries that aren’t plain exact matches. Word Search II matches many words against one input, and that input is a grid of letters.

When not to use it:

  • You only need exact membership. If every query is “is this whole string stored?”, a set does it in O(L) expected time, with far less memory and code.
  • You have one-off prefix queries on a list that never changes. Sort the words once. All words with prefix p then sit in one unbroken block, which you can find by binary search. There’s no tree to build.
  • The keys aren’t strings and the questions are about ranges (numbers, dates). That’s a job for a sorted structure, not a trie.

How it compares with its neighbours:

  • A hash set of all prefixes can answer “is p a prefix?” in O(len(p)). But it stores each prefix as a separate string. In the example that’s 23 characters for the 9 distinct prefixes, against 9 trie nodes. It also can’t list completions.
  • A sorted list plus binary search handles prefix ranges on data that doesn’t change. But it gets slow when inserts are frequent.
  • The trie stays O(L) for both insert and prefix queries, and it also lets you walk down into the matching words.

Pitfalls

  • Treating “the node exists” as “the word exists”. In the example, “ca” is a node but not a word. Every word query has to check end_count (or an is_end flag) on the node it lands on.
  • Creating nodes during a lookup. A common shortcut is to build the trie out of nested defaultdict objects. The trouble is that a lookup written as node = node[ch] then quietly creates nodes. I built “cat” and “car” that way, which gave 5 nodes including the root. Then I looked up “cow”, and the trie grew to 7 nodes. Use .get or an explicit in check every time you only mean to read.
  • Forgetting to count the root. If insert doesn’t increment root.pass_count, count_prefix(“”) returns 0 instead of the number of words.
  • Duplicates. A true/false end flag can’t count. Insert “a” twice and the flag still says there’s one “a”. Decide whether the problem needs counts.
  • The empty string. Inserting “” should mark the root as the end of a word. The loop body never runs, and that’s correct. But it only works if end_count is updated after the loop, not inside it.
  • Shared child objects. Say each node uses a list of 26 slots. Writing [TrieNode()] * 26 makes all 26 slots point to the same node (from memory: list multiplication copies references, not objects). Start every slot as None and create nodes only when you need them.
  • Complexity slips. If you compute a prefix count with a DFS instead of reading a stored pass_count, it costs O(L + K) rather than O(L). Under “c”, that’s a walk over 6 nodes instead of reading one integer. Recursion depth is another trap. Recursing once per character is fine for short words. But a recursive DFS on words thousands of characters long can hit Python’s default recursion limit (from memory: about 1000 frames).

Active Recall

  1. Starting from the five-word trie in the example, you insert “cart”. How many new nodes are created, and what are the “car” node’s pass_count and end_count afterwards?

  2. count_prefix(“car”) returns 3 but count_words(“car”) returns 1. Using only the invariant, explain why both answers come from the same node, and what a node with pass_count 4 and end_count 0 (like “ca”) tells you.

  3. Why is it safe for a lookup to return “not found” at the first missing child, without looking anywhere else in the trie?

  4. A friend suggests replacing the trie with a hash set holding every non-empty prefix of every word. For the five example words, how many entries would that set have, and what can the trie do that the set cannot?

  5. completions(“ca”) returned car, card, care, cat. If you removed sorted() from the DFS, what would it return for this insertion order, and why?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Skipped for this topic. Design Add And Search Words Data Structure and Word Search II never mention a trie. So both already make you decide to build one yourself, and then extend its walk. You’ll get that practice when you solve them in their own sessions.

Transfer test

You’re given up to 10,000 phone numbers, each up to 10 digits. The list is “consistent” if no number is a prefix of another number, because dialling the shorter one would connect before you finished the longer one. For example, 911 and 91125426 make a list inconsistent. You need to answer consistent or not. Would you use a trie? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Integration

There’s one prerequisite, and it has the same name as the topic, so the link is direct. Every problem in this list is the trie from the module plus one extra layer. What changes from problem to problem is who drives the walk:

  • The query drives the walk, along one path. This is exactly what the module built. You follow the characters of a string from the root, land on a node or fall off, and read the node’s counts or flags. Insert, word lookup and prefix lookup all have this shape.
  • The query drives the walk, but some steps branch. Sometimes a query character is allowed to match more than one child. Then the single walk turns into a DFS over the children that exist. It’s the same recursion completions uses below its prefix node. What the trie buys you here is that you only branch into children that are actually present.
  • Something outside the trie drives the walk. Sometimes the characters come from a different search, like a traversal of another structure or a scan through a text. Then the trie becomes a helper that the outer search asks at each step: “is the string so far still a prefix of some word, and is it a word?”. The early exit from Active Recall question 3 now lets the outer search prune, which means it can stop exploring a path early. This is where the trie meets the DFS from Trees and the choose/explore/un-choose loop that Backtracking formalizes. The append and pop around the recursive call in completions is that same move.

How to choose between competing approaches:

Situation Reach for Why
Exact membership only Hash set O(L) expected, less memory, no tree
Prefix queries on data that never changes Sorted list + binary search Words with a common prefix are contiguous after sorting
Inserts mixed with prefix queries, or listing completions Trie O(L) insert and prefix walk, and links to every extension
Query characters that can match several stored characters Trie with DFS over existing children Branches only where stored words actually differ
Many words searched for inside one input at the same time Trie of the words, walked by the outer search Shared prefixes are checked once; dead prefixes stop the search early

A recognition checklist for an unfamiliar problem:

  1. Is the data a collection of strings (or digit or bit sequences) over a small alphabet?
  2. Does any question mention prefixes, starts-with, autocomplete, or “is one of these a prefix of another”?
  3. Are many words matched against the same input, character by character, where an exact-match set would force you to check each word separately?
  4. Can a query character match more than one thing?
  5. Do inserts and queries interleave, so sorting once doesn’t cover it?
  6. Now decide. If only 1 is true and every query is an exact match, use a set. If 2 is true and the data never changes, try sorting plus binary search first. If 3, 4 or 5 is true alongside 1, build a trie. To decide what each node should store (an end flag, counts, something else), ask what the query needs to read when it lands on a node.

The problems

Work through these with the solving cycle from the method. Give each problem a 15-minute honest struggle, write one key sentence once it clicks, then review it with spaced repetition.

For tries, the questions to ask during the struggle are the same ones as for trees:

  • Can I combine results from the children of a node?
  • What does the call stack look like on a small example of three or four words? Rebuild it by hand.
  • How does information flow between the leaves and the root? What does the walk read on the way down, and what does a DFS report on the way back up?

3 problems · 0 easy · 2 medium · 1 hard · tracker spreadsheet (.xlsx)

#ProblemDifficultyCoach
1Implement Trie Prefix TreeMediumChatGPT · Claude
2Design Add And Search Words Data StructureMediumChatGPT · Claude
3Word Search IIHardChatGPT · Claude

Take this lesson as a live session

If you would rather be taught this interactively, with the coach waiting for your answers, open the whole lesson as a prompt in a chat.

Open the full lesson inChatGPT ↗Claude ↗