Trie and Prefix Indexing
Asked of: Software Engineer
Last updated

What's being tested
Tests construction and use of a Trie (prefix tree) for efficient prefix indexing, exact-word lookup, and longest-prefix matching. Interviewers probe correctness (terminal vs. prefix), per-node metadata for fast top-K or frequency-aware queries, and time/space complexity tradeoffs.
Patterns & templates
-
insert/search— traverse nodes per character, create child nodes as needed; O(L) time, O(1) extra space beyond nodes, where L is word length. -
Terminal flag vs. prefix — store
is_endboolean and optionally an exact-word payload to distinguish words from mere prefixes. -
Per-node metadata — keep
count,freq, ortopKlist at nodes to answer aggregate queries in O(L + K) time. Update these duringinsert/delete. -
Children representation — use hash map for variable alphabet or fixed array for small alphabets; memory ~O(total_chars) nodes × child-pointer-size.
-
Lazy deletion — clear
is_endand decrement metadata; prune nodes only when safe to avoid expensive recursive deletes. -
Longest-match replacement — greedy scan: advance as long as matching child exists and track last
is_end; overall O(N + M) for text size N and average match M per start. -
Collect/top-K traversal — DFS from prefix node, early-stop with maintained heap for K best; complexity O(nodes_in_subtrie + K log K).
Common pitfalls
Pitfall: Treating every node with children as a word—forgetting to check
is_endleads to false positives for exact search.
Pitfall: Failing to update per-node
topKon deletes/updates, causing stale suggestions.
Pitfall: Assuming constant alphabet; using fixed arrays for large Unicode input wastes memory.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
- Build Prefix Lookup with a TrieGoogle · Software Engineer · Technical Screen · medium
- Return Words Matching a Typed PrefixGoogle · Software Engineer · Onsite · medium
- Implement Trie Insert and Exact-Word SearchGoogle · Software Engineer · Technical Screen · medium
- Implement Longest-Match Text ReplacementGoogle · Software Engineer · Technical Screen · hard
- Design autocomplete with TrieGoogle · Software Engineer · Onsite · medium
Related concepts
- Sliding Window, Binary Search, and Prefix ReasoningCoding & Algorithms
- Trees, Tries, and Hierarchical DataCoding & Algorithms
- Search, Autocomplete And Restaurant DiscoverySystem Design
- Trees, Recursion, And BST TraversalCoding & Algorithms
- Trees And Hierarchical StructuresCoding & Algorithms
- Tree And Linked Structure AlgorithmsCoding & Algorithms