To determine whether a word exists in a Trie, we perform a character-by-character traversal starting from the root node. For each character in the search word, we check if the character exists in the current node's children. If it does, we move to that child node and continue. If we encounter a character that doesn't exist in the Trie at any point, we know immediately that the word does not exist, so we return false
.
However, reaching the end of the word isn't enough — we must also ensure that the last character leads us to a node that is explicitly marked as the end of a valid word. If not, then the word is only a prefix of some longer word and should still return false
.
Let’s consider some cases:
Normal case:
If we insert ["one", "only", "once"] and search for "once", we follow each letter until the end and confirm it ends at a valid word node. So, return true
.
Visualization
Prefix case:
Searching for "on" in the same Trie reaches valid characters but doesn’t hit an end-of-word node, so we return false
.
Visualization
- Empty Trie: If no words are inserted, any search word will return
false
because the Trie is completely empty.
- Empty string search: Searching with an empty string is often considered invalid unless explicitly allowed. In most Trie implementations, this will return
false
.
This operation is highly efficient — its time complexity is O(m)
, where m
is the length of the search word, making it much faster than linear search for large sets of words.