How it works
For a small catalog, a normalized indexed range query may suffice: in Postgres, a B-tree on the lowercased term can answer “every term from ca up to cb.” A trie is a tree with one edge per character, so terms that share a prefix share a path. Following edges reaches a prefix node; a terminal marker distinguishes a complete submitted query from a mere prefix. Prefix lookup costs O(p) for input length p, but that says nothing about the cost of finding the best descendants.
Consider terms with example counts: car (900), card (700), cat (600), care (400), cup (100). The node for “ca” has four descendants, and the top two are car and card. That is easy at this size. In a catalog of 50 million terms, the node for “s” may have millions of descendants, and scanning and sorting them on every keystroke is too expensive. Store a bounded top-K list at selected nodes, or materialize a prefix-to-top-K map. That trades memory and build work for fast reads: 20 million prefixes × 10 candidates × 40 bytes is 8 GB before overhead.
A compressed trie, sparse map, or database index may fit better depending on vocabulary size, update rate, and language. Elasticsearch’s completion suggester, for instance, uses an in-memory finite state transducer, a compact relative of the trie. A trie answers only prefixes: matching “york” inside “new york” requires indexing each word or using n-grams, at more memory. Capping input length bounds p only if enforced; it does not make arbitrary lookup inherently O(1).
The prefix “a” has a million descendants. Why can a basic trie still be slow?
Finding the “a” node is cheap; scanning and ranking all descendants is not. Precompute candidates for broad prefixes or choose another ranked index.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Prefix lookup and top-K selection have separate costs.
- Precomputed top-K lists trade memory and rebuild work for low read latency.