Trie is an ordered tree data structure which stores words in it so that users can search a word or a prefix quickly. Time complexity for adding a word to a Trie is $O(l)$, and for searching a word or a prefix is $O(l)$ too ($l$ is the length of the word or the prefix being added or searched). So it’s why we prefer Trie rather than Set and Hash Table in some situations, such as Dynamic Set, Associative Array and a predictive text or autocomplete Dictionary.

Definition

• The Trie is a tree where each node represents a single word or a prefix.
• The root represents an empty string (“”), the nodes that are direct children of the root represent prefixes of length $1$, the nodes that are $2$ edges of distance from the root represent prefixes of length $2$, the nodes that are $3$ edges of distance from the root represent prefixes of length $3$ and so on. In other words, a node that is $k$ edges of distance of the root has an associated prefix of length $k$.
• Let $v$ and $w$ be two nodes of the Trie, and assume that $v$ is the parent of $w$, then $v$ must have an associated prefix of $w$.

The figure below shows a Trie with the words “TREE”, “TRIE”, “ALGO”, “ASSOC”, “ALL”, and “ALSO.” Trie

LeetCode Problem

211. Add and Search Word - Data structure design

Design a data structure that supports the following two operations:
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters “a-z” or “.”. A “.” means it can represent any one letter.