Skip to the page

Recursion, trees and heaps · mid

Tries for prefix search

A trie stores words character by character in a tree, so 'all words with this prefix' costs O(length of prefix) to find the node plus the size of the results, which is why it backs autocomplete and word break.

The notes

What you must know

  • Node = a map from character to child node (or an array of 26 slots for lower-case letters) plus an 'end of word' flag, and optional data such as a count.
  • insert, search (whole word: the end flag must be true) and startsWith (the prefix exists): each O(L) for word length L.
  • Suggestions: walk to the prefix node, then DFS collecting words; visit children in sorted order for alphabetical results, or keep the top k by frequency at each node for ranking.
  • Memory is the cost: many small nodes. An array of 26 children is fast but large; a hash map per node is smaller for sparse data. For a few thousand words, a sorted array with binary search is often enough; say so.
  • Case and Unicode: normalise the text (lower case, one Unicode form) before inserting and searching.
  • Uses: autocomplete, spell check, word break with a big dictionary, prefix matching for IP addresses and routes.

The red pen

Common traps: mistake → fix

  • Mistake: search('ca') is true if 'car' was inserted

    Fix: only startsWith is; search needs the end flag.

  • Mistake: A trie is always better than filtering a list

    Fix: for small lists, a simple filter is clearer and fast enough.

  • Mistake: Suggestions come out alphabetically by themselves

    Fix: a hash map does not keep order; sort the child keys.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement insert, search and startsWith.
  2. Return the first k suggestions for a prefix.
  3. Rank suggestions by popularity instead of alphabet.
  4. When would you not use a trie?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview