Skip to content
Veltoryx Technologies
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 in O(L) time, where L is 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 ch maps to index ch - 'a'.
  • isWord indicates that a complete word terminates at this node, distinguishing whole words from intermediate prefixes.

022. Core operations

  1. 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, set node.isWord = true.
  2. search(word): Walk letter by letter. If any child link is missing, return false. When the string is consumed, return node.isWord.
  3. startsWith(prefix): Walk letter by letter. If all characters exist, return true immediately regardless of whether node.isWord is 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.