Skip to content
Lesson 3 of 8

Step 1 of 5 · Reading · ~1 min

Read

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

Up nextDeletionSearch & Prefix

Discussion

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

Sign in to post a comment or reply.

Loading…