Trie (Prefix Tree)

A tree keyed by characters, where the path from the root spells a prefix: lookup, insert and prefix search in time proportional to the word length, not the number of words.

Overview

A trie stores strings as paths. The root is the empty string; each edge adds one character; a node is marked when the path to it is a whole word. To look up a word you walk one edge per character, so the cost depends on the length of the word (call it L) and not on how many words are stored. The name comes from retrieval; Edward Fredkin described the structure as trie memory in 1960.

A hash set also finds a word in about O(L) time, because hashing reads every character. What the hash set cannot do is answer a prefix question: every word starting with ca is one walk in a trie and a full scan in a hash set. Prefix questions are why tries exist: autocomplete, spell checking, longest-prefix matching in routers, and word counting by prefix.

Three structures can hold a word list, and each trades lookup speed, prefix questions, order and memory differently.

  • Hash set: an exact lookup is O(L). All words with a prefix cost O(n), a scan of everything. It keeps no sorted order. Memory is low: one entry per word.
  • Sorted array: an exact lookup is O(L log n). A prefix takes O(log n) to find the first match, then a scan of the run. It is sorted, and it uses the least memory of the three.
  • Trie: an exact lookup is O(L). A prefix takes O(L) to reach the prefix node, then a walk of the subtree. An in-order walk gives sorted order. Memory is high: one node per distinct prefix.

So a trie spends memory to make prefix questions as cheap as exact lookups. The rest of this chapter shows how it is built.

The structure

Each node holds its children, keyed by character, and a flag that says a word ends here. A count of words below the node is optional; it makes prefix counts O(L).

In code that is two classes. A Trie holds one private TrieNode, its root, and offers insert(word), search(word), starts_with(prefix) and delete(word); the last three return a bool. A TrieNode holds a dict of children, a bool is_end and an int count, and each node owns zero or more child nodes. The root is an ordinary node with no character of its own, and a word is a path of nodes that ends on one flagged is_end.

Interview questions

  • Implement autocomplete: return the top k words for a prefix.
  • Support wildcard search, where a dot matches any one character.
  • A trie of a million words uses too much memory. What are the options?
  • Count the words that start with a given prefix in O(L).
  • How do you make the trie safe for concurrent readers and writers?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio