Skip to content
Visual explainer 2h 30m to learn 4 steps

Tries (prefix trees)

Implement a trie and use it for prefix search and autocomplete.

By Invicly Tech, , in Data Structures & Algorithms. About 10 minutes to read.

Topic 30 of 54

In short

A trie stores strings character by character along paths from the root, so words with a common prefix share nodes. Lookup and insert cost O(L) for a word of length L, independent of how many words are stored. Tries shine for prefix search, autocomplete and word games.

Explained simply

A trie (often said like "try") is a tree for storing words. Each step down the tree adds one letter. Words that start the same way share the same path at the top. So 'car', 'cat' and 'cart' all share the c-a path.

Finding a word is like following road signs letter by letter. To check 'cat', go to c, then a, then t. If at any point the next letter is missing, the word is not stored. The time depends only on the length of the word, not on how many words are in the trie.

Each node also needs a small flag that says "a word ends here". Without it, you could not tell whether 'car' is a stored word or just the beginning of 'cart'.

Tries are perfect for questions about beginnings of words. "Which words start with 'ca'?" is answered by walking to the c-a node and listing everything below it. This is how simple autocomplete and spell-check suggestions work.

Press Play on a diagram to walk through it one step at a time.

MapTrie holding car, cat, cup (below root and shared c)
c
  • a
    • r (end): car
    • t (end): cat
  • u
    • p (end): cup
CompareStoring a word list
Hash set
  • Exact lookup O(L) average
  • No prefix queries
  • Compact in memory
  • Built into Python
Sorted list + bisect
  • Lookup O(L log n)
  • Prefix = one contiguous block
  • Very compact
  • Insert O(n)
Trie
  • Lookup and insert O(L)
  • Prefix queries O(P) plus results
  • Many node objects
  • Prefix counts, longest prefix match

In depth

Node design and memory cost

There are two common node designs. A dict of children (like the explainer's version) stores only the letters actually used, which suits large alphabets such as Unicode. An array of 26 slots for lowercase letters gives fast indexing but wastes memory when most slots are empty.

The number of nodes is at most the total number of characters inserted, plus one for the root, and shared prefixes reduce it. But each Python node is a separate object, often a few hundred bytes. A trie of 100,000 English words can easily use tens of megabytes in Python, far more than a set of the same words.

Compressed tries, called radix trees or Patricia tries, merge chains of single-child nodes into one edge labelled with a whole substring. This cuts the node count dramatically. Radix trees are used for IP routing tables and inside many key-value stores and web routers.

  • Dict children: flexible, any alphabet
  • Array of 26: fast, memory hungry
  • Radix tree: merge single-child chains

Insert, search and startsWith

Insert walks the word letter by letter, creating missing children, and sets the end flag on the last node. Search walks the same path; it fails if a letter is missing, and succeeds only if the final node has the end flag. startsWith walks the prefix and succeeds if the walk completes, regardless of the flag.

All three cost O(L) for a string of length L. That cost does not grow with the number of stored words, which is the trie's selling point. A hash set lookup is also O(L) on average, because hashing the string reads every character, so for exact lookups a set is usually faster in Python.

Useful extras: store a count of words passing through each node to answer "how many words start with this prefix" in O(L). Store the full word or a frequency at end nodes for autocomplete ranking. Deletion clears the end flag and then removes nodes on the way back up that have no children and no flag.

Flowsearch('cap') versus startsWith('ca')
  1. Step 1
    Root to c

    Child c exists.

  2. Step 2
    c to a

    Child a exists: startsWith('ca') is True.

  3. Step 3
    a to p?

    No child p: search('cap') is False.

  4. Step 4
    Rule

    search also needs the end flag at the last node.

Autocomplete: collecting words under a prefix

Walk to the prefix node in O(P). Then run a DFS over its subtree, building the current string as you go and recording it whenever you reach an end flag. Visiting children in alphabetical order (sort the dict keys, or use the 26-slot array) yields suggestions in sorted order. Stop after k results to keep it fast.

The cost is O(P + size of the subtree visited). For a short prefix like 'a', the subtree might be huge, which is why real autocomplete systems precompute the top few suggestions at each node, or rank by stored frequency and use a heap to pick the best k.

Tries also power word games and grid searches. In Word Search II, you DFS over a letter grid while walking the trie in parallel, abandoning a path as soon as the trie has no matching child. One trie handles thousands of target words at once.

  • Walk to prefix, then DFS for end flags
  • Sorted child order gives sorted results
  • Prune grid searches when the trie has no child

Tries versus hash sets and sorted lists

A hash set answers "is this exact word stored?" in O(L) average time with low memory and C-speed hashing. It cannot answer prefix questions without scanning every word.

A sorted list with bisect answers prefix questions surprisingly well: all words with prefix p lie in one contiguous block starting at bisect_left(words, p). Walk forward while words start with p. That is O(L log n) to find the block, and very memory efficient. Inserting new words is O(n), though.

A trie gives O(L) insert, search and prefix queries, plus extras: longest common prefix, the longest stored prefix of a query (used in routing and tokenisers), and prefix counts, all naturally. Choose a trie when prefix operations are the core of the problem and data changes often; otherwise a set or sorted list is simpler in Python.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Implement insert and search~40m
  2. 2
    Answer startsWith prefix queries~40m
  3. 3
    Collect words for autocomplete~40m
  4. 4
    Compare tries with hash sets~40m

Key points

  • Insert, search and startsWith: O(L) time.
  • Space can be large: up to one node per character inserted.
  • An end-of-word flag distinguishes car from a prefix of cart.
  • Hash sets answer exact lookups but not prefix queries efficiently.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
class Trie:
    def __init__(self): self.root = {}

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

    def _walk(self, s):
        node = self.root
        for ch in s:
            if ch not in node: return None
            node = node[ch]
        return node

search(w) checks '$' in _walk(w); starts_with(p) checks _walk(p) is not None.

Trie with prefix counts and autocomplete

Each node is a dict of children plus a count of how many words pass through it and an end flag. After inserting 'car', 'card', 'care', 'cat' and 'dog', count_prefix('car') is 3 and complete('car') returns ['car', 'card', 'care'] in alphabetical order, by walking to the prefix node and doing a sorted DFS.

python
class TrieNode:
    def __init__(self): self.kids, self.count, self.end = {}, 0, False

class Trie:
    def __init__(self): self.root = TrieNode()
    def insert(self, w):
        n = self.root
        for ch in w:
            n = n.kids.setdefault(ch, TrieNode()); n.count += 1
        n.end = True
    def _walk(self, p):
        n = self.root
        for ch in p:
            n = n.kids.get(ch)
            if n is None: return None
        return n

Longest common prefix of a word list

Insert all words into the trie, then walk down from the root while the current node has exactly one child and is not the end of a word. For ['flower', 'flow', 'flight'] the walk goes f, l and then stops because l has two children (o and i). The answer is 'fl'. A single-node trie dict keeps this short.

python
def longest_common_prefix(words):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node['$'] = True
    prefix, node = [], root
    while len(node) == 1 and '$' not in node:
        ch = next(iter(node))
        prefix.append(ch)
        node = node[ch]
    return ''.join(prefix)

print(longest_common_prefix(['flower', 'flow', 'flight']))  # fl

Quick reference

  • Insert, search, startsWith: O(L) for a string of length L
  • search needs the end flag; startsWith only needs the path
  • Store a pass-through count per node to count words with a prefix in O(P)
  • Autocomplete: walk to the prefix node, then DFS collecting end flags
  • Radix tree: compress single-child chains into one edge
  • Exact lookups only? A Python set is simpler and faster
  • Sorted list: words with prefix p start at bisect_left(words, p)

Common mistakes

  • Forgetting the end marker, so prefixes are reported as words.
  • Using a trie for a handful of exact lookups where a set is simpler.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A trie holds 'cart' only. What do search('car') and startsWith('car') return?

Question 2

2What is the time to search a word of length L in a trie with a million words?

Question 3

3What does a radix (compressed) trie change?

Question 4

4Which question can a trie answer efficiently that a hash set cannot?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add search(w) and starts_with(p) to the Trie class from the first example. Example: after inserting 'car', search('ca') is False and starts_with('ca') is True.

  2. Exercise 2medium

    Add complete(p, k=10) to the Trie class that returns up to k stored words starting with p, in alphabetical order. Example: after 'car', 'card', 'care', 'cat', complete('car') gives ['car', 'card', 'care'].

  3. Exercise 3hard

    Write replace_words(roots, sentence) that replaces each word with the shortest root that is its prefix. Example: roots ['cat', 'bat', 'rat'], sentence 'the cattle was rattled by the battery' gives 'the cat was rat by the bat'.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do you pronounce trie?
Most people say "try" to avoid confusion with "tree", although the name comes from retrieval and some say "tree".
Is a trie faster than a dict in Python?
For exact lookups, usually no: a dict or set hashes the whole string in fast C code. A trie wins when you need prefix queries, prefix counts or longest-prefix matching.
Where are tries used in real systems?
In autocomplete and spell checkers, IP routing (longest prefix match on addresses), tokenisers that match the longest known piece, and URL routers in web frameworks, often in compressed radix-tree form.

Go deeper

ShareXLinkedInWhatsApp