Skip to the page

Recursion, trees and heaps · mid

Tries for autocomplete

A trie stores words character by character in a tree of Maps, 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 = { children: Map<char, Node>, end: boolean } (plus optional data such as a frequency or an id).
  • insert, search (whole word: end must be true), startsWith (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 top-k by frequency at each node for ranking.
  • Memory is the cost: many small objects. For a client-side autocomplete with a few thousand items, a sorted array + binary search or a simple filter may be enough — say so.
  • Case and Unicode: normalise (toLowerCase, normalize('NFC')) before inserting and searching.
  • Uses: typeahead, emoji search by name, word break with a big dictionary, IP/route prefix matching.

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 filter()

    Fix: for small lists, filter is simpler and fast enough.

  • Mistake: Suggestions come out alphabetically by themselves

    Fix: Map keeps insertion 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 on the client?

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