Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN

Trie (Prefix Tree): O(L) Prefix & Autocomplete Lookup

Share common character prefixes as tree edges so lookup speed depends only on query length, never dictionary size.

trietreesstringsautocompleteprefix

The core idea

Hash sets only test exact full-string equality. A Trie turns every character into a tree edge, letting you check prefixes or branch on wildcards in O(L) time even with millions of stored commands.

Watch it run

Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.

LOADING TRIE PREFIX TREE SIM...

What to say out loud

Canonical Python template

class Trie:
    def __init__(self):
        self.root: dict = {}

    def insert(self, word: str) -> None:
        cur = self.root
        for ch in word:
            cur = cur.setdefault(ch, {})
        cur["$"] = True

    def starts_with(self, prefix: str) -> bool:
        cur = self.root
        for ch in prefix:
            if ch not in cur:
                return False
            cur = cur[ch]
        return True

Related Lab Entries