Data Structures · Visualization
Trie: Search
Trie
Searching for an exact word walks down the trie following each character of the word in order. Time: O(L), where L is the word's length. Space: O(1) extra.
Big-O: Lookup O(word length), independent of the number of words.
Trie: Search
TrieSearching for an exact word walks down the trie following each character of the word in order. If at any point the needed character edge doesn't exist, the word isn't in the trie. If all characters are found, the word only counts as present if the final node is specifically marked 'end of word' (otherwise it might just be a prefix of some other word).
How Search Works
- Start at the root.
- For each character in the word, check if a matching child edge exists.
- If it doesn't exist at any point, the word is not in the trie — stop.
- If all characters are matched, check whether the final node is marked 'end of word'.
Search Worked Example
Input: Search for 'do' in a trie containing 'dog' and 'do'
- root -> d (exists) -> o (exists)
- All characters matched — now check the 'o' node's end-of-word flag
- Flag is true (since 'do' was inserted) → word found
Output: true (found)
Press ▶ Run to watch it step by step.
def search(root, word):
cur = root
for ch in word:
if ch not in cur.children:
return False
cur = cur.children[ch]
return cur.is_end # must be a full word
# O(word length)
# example: search "do"Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Search Time & Space Complexity
When to Use Search
- Validating whether a typed word exists in a dictionary
- Checking if a search term matches a known product name exactly
- Fast exact-match lookup after narrowing by prefix
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.