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

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. 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

  1. Start at the root.
  2. For each character in the prefix, check if a matching child edge exists.
  3. If it doesn't exist at any point, no word starts with this prefix — stop.
  4. 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'

  1. root -> c (exists) -> a (exists)
  2. All prefix characters matched — no need to check end-of-word

Output: true (at least one word starts with 'ca')

Try your own input
Trie: Introduction
A tree where each path from the root spells out a word one character per edge — words sharing a prefix share the same starting path.
root
root
c
a
t
r
t
d
o
g
n
e
Active path End of word
Trie: Introduction
Press ▶ Run to watch it step by step.
Python · Tries in Code
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"
Input: Check prefix 'ca' in a trie containing 'cat' and '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

TimeO(L), where L is the prefix's length
SpaceO(1) extra

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.