FreeLesson 13.1Beginner1 min readUpdated 30 October 2026
The pattern: trie
Master prefix trees for efficient string insertion, prefix lookup, autocomplete, and wildcard pattern matching.
A Trie (derived from retrieval, pronounced "try") is a specialized tree data structure designed for storing and searching strings over an alphabet. Instead of storing entire strings in individual nodes, each node represents a single character, and words are represented by paths from the root to marked terminal nodes.
Tries excel at prefix-based operations that standard hash tables cannot efficiently perform:
- Prefix matching (
startsWith): Find whether any stored word begins with a given prefix inO(L)time, whereLis prefix length. - Autocomplete & dictionary searching: Traverse down to the prefix node and explore the subtree.
- Wildcard search: Branch across all children when a wildcard character (like
'.') is encountered using depth-first search.
011. Node representation
For lowercase English letters a-z, each node typically contains an array of 26 references:
text
class TrieNode {
TrieNode[] next = new TrieNode[26];
boolean isWord = false;
}- Character
chmaps to indexch - 'a'. isWordindicates that a complete word terminates at this node, distinguishing whole words from intermediate prefixes.
022. Core operations
insert(word): Walk letter by letter starting at the root. If a child link does not exist, instantiate a new node. After traversing the final character, setnode.isWord = true.search(word): Walk letter by letter. If any child link is missing, returnfalse. When the string is consumed, returnnode.isWord.startsWith(prefix): Walk letter by letter. If all characters exist, returntrueimmediately regardless of whethernode.isWordis set.
033. Wildcard matching (Backtracking with Trie)
When searching with wildcards (e.g. '.' matches any character), exact character lookup is replaced by branching:
- Regular letter: follow the single child link
node.next[ch - 'a']. - Wildcard
'.': iterate through all non-null children and recursively continue search.