Data Structures · Visualization
Trie: Starts With
Trie
Checking a prefix works almost like searching for a full word, except you don't check the 'end of word' flag at the end — you only care whether the path for those characters exists at all. Time: O(L), where L is the prefix's length. Space: O(1) extra.
Big-O: Lookup O(word length), independent of the number of words.
Trie: Starts With
TrieChecking a prefix works almost like searching for a full word, except you don't check the 'end of word' flag at the end — you only care whether the path for those characters exists at all. This is what powers autocomplete: if the prefix path exists, there is at least one word in the trie that starts with it.
How Starts With Works
- Start at the root.
- For each character in the prefix, check if a matching child edge exists.
- If it doesn't exist at any point, no word starts with this prefix — stop.
- If all characters of the prefix are matched, at least one word starts with it, regardless of end-of-word flags.
Starts With Worked Example
Input: Check prefix 'ca' in a trie containing 'cat' and 'car'
- root -> c (exists) -> a (exists)
- All prefix characters matched — no need to check end-of-word
Output: true (at least one word starts with 'ca')
Press ▶ Run to watch it step by step.
def starts_with(root, prefix):
cur = root
for ch in prefix:
if ch not in cur.children:
return False
cur = cur.children[ch]
return True # any word with this prefix
# O(prefix length)
# example: starts with "car"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.
Starts With Time & Space Complexity
When to Use Starts With
- Powering search-as-you-type / autocomplete suggestions
- Filtering a list of results down as a user types more characters
- Prefix-based routing or matching systems
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.