Build a Ranked Autocomplete Trie for Search Suggestions

Last updated: November 29, 2026

Quick Overview

Design a structure that records search queries with their frequencies and, for any typed prefix, returns the top k most frequent past queries starting with that prefix, breaking ties alphabetically.

Microsoft
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Design a structure that records search queries with their frequencies and, for any typed prefix, returns the top k most frequent past queries starting with that prefix, breaking ties alphabetically.

Bing and the Windows search box both serve prefix suggestions on every keystroke, so Microsoft interviewers use this to see whether you shift work from read time to write time. They look for a trie, a clear argument for why caching top k per node stays correct, and an honest discussion of memory.

What the Interviewer Expects
  • Uses a trie keyed by character for prefix lookup
  • Precomputes top k per node so suggest is O(prefix length)
  • Argues correctness of per-node top k when counts only increase
  • Defines deterministic tie-breaking
  • Discusses memory cost and the offline-build alternative used at web scale
Key Topics to Cover
Trie
Top-k
Precomputation
Caching at write time
Search suggestions
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you support decrements or deleting a query (for example, removing offensive suggestions)?
  • How would you personalize suggestions per user without one trie per user?
  • How would you shard this when the query log has billions of distinct queries?
  • How would you tolerate typos in the prefix?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

record(query, times) increases a query's count. suggest(prefix) returns up to k queries with that prefix ordered by count descending, then alphabetically. Reads vastly outnumber writes (every keys...

High-Level Design

A trie gives O(L) prefix lookup. The naive suggest then DFSes the whole subtree and picks the top k, which is too slow for short prefixes like w. Instead, each node stores the current top k queries ...


Submit Your Answer
Markdown supported