Skip to content
Prefix Search
step 1/5

Reading — step 1 of 5

Read

~1 min readSearch & Prefix

Prefix Search

The killer feature: "find all words starting with pre".

python

Time complexity:

  • Walk to prefix: O(|prefix|)
  • DFS: O(K) where K is total characters in matched words

For "ar*" prefix on a trie of 100k words, this is hundreds of times faster than scanning all words.

Sorted output: iterate child dict in sorted order. For ASCII a-z this is automatic if you store children in an array.

For autocomplete UIs you typically want TOP-K by frequency, not all matches. Maintain an aggregate "most-frequent word in subtree" pointer at each node for O(K) top-K.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…