AlgoViz

Trie (prefix tree)

medium 20 min

A trie (pronounced "try") is a tree that stores strings one character per level, so words with the same opening letters share the same path from the root.

Video lesson · Chapter 1 of 8

The sign maker’s catalogue

0:00 / 6:15

The trie in 75 seconds

1:19Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

One letter per level. Each edge is a character, so every path from the root spells a prefix

Understand it

Start here

A tree of letters

A trie (from retrieval, usually said "try") stores a set of strings as a tree. The root holds no letter. Each child edge adds one character, so the path from the root to any node spells a prefix, and a flag on the node says whether a whole word ends there. Words that start the same way share their path: cat, car, card and care all hang off one c → a chain.

What you already know

  • Tree DFS

    Collecting every word below a node is a plain preorder DFS. Recap in tree DFS.

  • Hash maps

    Each node keeps its children in a dict from letter to node: O(1)O(1) average per step. Recap in hash usage.

  • Sets and maps

    A set answers "is this word stored?" but not "which words start with ca?". Recap in sets and maps.

The picture

One path per word

Trie for cat, car, card, care

Six letter nodes store 14 letters. The r node is both the end of car and the parent of d and e.
NodePrefix it spellsis_endChildren
root(empty)Falsec
ccFalsea
acaFalset, r
tcatTruenone
rcarTrued, e
d, ecard, careTruenone
A node never stores its whole word. The word is the path that leads to it.

The node

Dict of children or a 26-slot array

Dict of childrenArray of 26 slots
Child lookupO(1)O(1) average (hashing)O(1)O(1) exact: kids[ord(ch) - 97]
Memory per nodeOnly the children that exist26 pointers, most of them empty
AlphabetAny character: Unicode, digits, spacesFixed, usually lowercase a to z
Children in orderInsertion orderAlphabetical for free
Typical usePython interviews, real textFixed small alphabets, C++ and Java contests
Python
class DictNode:    def __init__(self):        self.children = {}          # only letters that exist        self.is_end = Falseclass ArrayNode:    __slots__ = ("kids", "is_end")    def __init__(self):        self.kids = [None] * 26     # one slot per letter a..z        self.is_end = Falsedef child(node, ch):    return node.kids[ord(ch) - ord("a")]n = ArrayNode()n.kids[ord("c") - ord("a")] = ArrayNode()print(child(n, "c") is not None, child(n, "d"))   # True None
Both layouts. The rest of the trie code is the same apart from how a child is found.
Edit and run it in your browser

Operation 1

Insert

insert(word)

Existing nodes are reused, so a word that extends a stored prefix adds only its new letters.

Insert car into a trie that holds cat

  1. 1

    Letter c

    At the root, child c already exists (from cat). Step down, create nothing.

  2. 2

    Letter a

    Child a exists too. Step down.

  3. 3

    Letter r

    No child r yet: create it and step down.

  4. 4

    Mark the end

    Letters used up: set is_end = True on r. One new node for a three-letter word.

Python
class TrieNode:    def __init__(self):        self.children = {}        self.is_end = Falseclass Trie:    def __init__(self):        self.root = TrieNode()    def insert(self, word):        node = self.root        for ch in word:            if ch not in node.children:                node.children[ch] = TrieNode()            node = node.children[ch]        node.is_end = True    def _find(self, s):        node = self.root        for ch in s:            if ch not in node.children:                return None            node = node.children[ch]        return node    def search(self, word):        node = self._find(word)        return node is not None and node.is_end    def starts_with(self, prefix):        return self._find(prefix) is not Nonet = Trie()t.insert("cat")t.insert("car")print(t.search("cat"), t.search("ca"), t.starts_with("ca"))   # True False True
The complete trie: insert, search, starts_with.
Edit and run it in your browser

Operations 2 and 3

Search vs starts_with

One walk, two answers

The only difference is the final is_end check.
Call (trie holds cat, car, card, care)PathResultWhy
search('car')c, a, r foundTruer is marked as an end
search('ca')c, a foundFalsea is not an end: a prefix only
search('cow')breaks at oFalsec has no child o
starts_with('ca')c, a foundTruefour words sit below a
starts_with('do')breaks at dFalsethe root has no child d

Operation 4

Delete without breaking other words

delete(word), recursively

Pruning walks back up and stops at the first node that is still useful.
  • Only unmark

    Delete car while card and care exist: r keeps its children, so just clear is_end.

  • Prune a tail

    Delete card: d is a childless leaf, so it is cut off. Pruning stops at r because e still hangs below.

  • Not present

    Delete dog: the root has no child d. Return without changing anything.

Complexity

O(L) per operation, O(total characters) space

OperationTimeExtra space
insert(word)O(L)O(L)up to LL new nodes
search(word)O(L)O(L)O(1)O(1)
starts_with(prefix)O(m)O(m)O(1)O(1)
delete(word)O(L)O(L)O(L)O(L) recursion
autocompleteO(m+k)O(m + k)O(k)O(k) for the answers
LL = word length, mm = prefix length, kk = letters in the subtree below the prefix node.

Time: one step per character

T(L)=∑i=1LO(1)⏟child lookup=O(L)independent of n, the number of wordsT(L) = \sum_{i=1}^{L} \underbrace{O(1)}_{\text{child lookup}} = O(L) \quad \text{independent of } n \text{, the number of words}
With a dict the O(1)O(1) is an average (hashing); with a 26-slot array it is exact.

Space: at most one node per stored character

#nodes  ≤  1+∑w∈W∣w∣array layout: O(σ⋅∑w∣w∣) pointers\#\text{nodes} \;\le\; 1 + \sum_{w \in W} |w| \qquad \text{array layout: } O\Big(\sigma \cdot \sum_{w} |w|\Big) \text{ pointers}
Shared prefixes push the count below the bound: 14 letters in cat, car, card, care need 6 letter nodes. With an alphabet of size σ=26\sigma = 26, each array node pays for 26 slots, used or not.

Application

Autocomplete: collect words under a prefix

Autocomplete in two phases

Phase one costs O(m)O(m), phase two O(k)O(k). Search engines store a count on each end node to rank suggestions.
Words in the triePrefixSuggestions
app, apple, application, api, code, coding, computer, data, databaseappapp, apple, application
cat, car, card, care, dog, dolphin, dove, bear, bee, birdcarcar, card, care
pizza, pie, pasta, pan, pancake, burger, burrito, bread, butterpapasta, pan, pancake
how to code (1000), how to learn python (900), how to cook pasta (800), how are you (500), ...howranked by count: how to code first
The tech, animals, food and search engine examples. Each needs only as many hops as the prefix has letters.
Python
class Node:    def __init__(self):        self.children = {}        self.freq = 0               # > 0 means a query ends heredef add(root, text, freq):    node = root    for ch in text:        node = node.children.setdefault(ch, Node())    node.freq = freqdef suggest(root, prefix, k=3):    node = root    for ch in prefix:        if ch not in node.children:            return []        node = node.children[ch]    found = []    def dfs(n, text):        if n.freq:            found.append((-n.freq, text))        for ch, c in n.children.items():            dfs(c, text + ch)    dfs(node, prefix)    return [t for _, t in sorted(found)[:k]]root = Node()for q, f in [("how to code", 1000), ("how to cook pasta", 800),             ("how to learn python", 900), ("how are you", 500),             ("weather today", 2000)]:    add(root, q, f)print(suggest(root, "how"))# ['how to code', 'how to learn python', 'how to cook pasta']
Autocomplete with a frequency on each end node, best first.
Edit and run it in your browser

Choosing

Trie vs hash set

QuestionHash set of wordsTrie
Is word stored?O(L)O(L) average (hash the word)O(L)O(L)
Any word starting with p?O(n⋅m)O(n \cdot m): test every wordO(m)O(m)
All words starting with pO(n⋅m)O(n \cdot m)O(m+k)O(m + k)
Sorted orderNoYes, with ordered children
MemoryOne entry per wordOne node per distinct prefix; can be larger
Code to writeNone: set() is built inA small class

Use a trie when

  • You need autocomplete or typeahead.
  • Spell checking or suggestions by prefix.
  • IP routing: longest prefix match.
  • Word games: Boggle, word search, Scrabble helpers.
  • Searching with wildcards such as c.t.

Use something else when

  • You only need exact lookups: a hash set or dict is simpler.
  • Memory is tight: tries can be large.
  • There are few strings and no prefix questions.
  • You need ranges over numbers: a sorted array or balanced tree.

Classic problems

Word Search II and longest common prefix

Word Search II: given a letter grid and a list of words, find every word that can be traced through adjacent cells. Running one grid search per word repeats the same work. Instead, put all the words in a trie and run one backtracking DFS from each cell, moving down the trie as you move across the grid. The moment the current path is not a prefix of any word, the trie has no child for it and the branch is cut.

Word Search II: grid DFS guided by a trie

Clearing the end flag stops the same word being reported twice. Pruning childless trie nodes as words are found speeds it up further.
Python
def longest_common_prefix(words):    if not words:        return ""    root = {}    END = "$"    for w in words:        node = root        for ch in w:            node = node.setdefault(ch, {})        node[END] = True    prefix = []    node = root    while len(node) == 1 and END not in node:        ch = next(iter(node))        prefix.append(ch)        node = node[ch]    return "".join(prefix)print(longest_common_prefix(["flower", "flow", "flight"]))   # flprint(longest_common_prefix(["car", "card", "care"]))        # car
Longest common prefix: insert every word, then walk down while there is exactly one child and no word ends.
Edit and run it in your browser

Problems that are tries in disguise

  • Implement a trie

    insert, search, starts_with: the three methods on this page.

  • Add and search with wildcards

    A . matches any letter: at that position, try every child.

  • Word Search II

    Many words on one grid: one DFS guided by a trie of all the words.

  • Replace words

    Swap each word for its shortest root: walk until the first end flag.

In the wild

Where tries run

  • Search boxes

    Google, Amazon and YouTube suggest completions as you type, ranked by how often each query is searched.

  • Spell checkers

    Walk the trie to test a word and explore nearby branches for suggestions.

  • IP routing

    Routers pick the most specific rule for an address with a longest-prefix match on a binary trie.

  • Word games

    Boggle and Scrabble helpers prune any letter path that is not a prefix of a real word.

Recap

Key takeaways

Key points

  • A trie stores strings one character per level; words with a common prefix share nodes.
  • Each node has children (a dict or a 26-slot array) and an is_end flag.
  • insert, search and starts_with are O(L)O(L), independent of how many words are stored.
  • search checks is_end; starts_with does not.
  • Delete unmarks the end, then prunes nodes that are not ends and have no children.
  • Space is at most one node per stored character, O(∑∣w∣)O(\sum |w|).
  • Autocomplete is a prefix walk plus a DFS: O(m+k)O(m + k).
  • Prefer a hash set for exact lookups only; reach for a trie when prefixes matter.

Sources