Return Top Three Search Suggestions Ranked by Query Popularity
Last updated: November 29, 2026
Quick Overview
Build an autocomplete component for the TikTok search bar: `record(query, times)` adds to a query's popularity and `suggest(prefix)` returns the three most popular queries starting with that prefix, ties broken alphabetically. Suggestions must be fast because they run on every keystroke.
TikTok
November 29, 20260
0
0 solved
Build an autocomplete component for the TikTok search bar: `record(query, times)` adds to a query's popularity and `suggest(prefix)` returns the three most popular queries starting with that prefix, ties broken alphabetically. Suggestions must be fast because they run on every keystroke.
Search suggestions are a core TikTok surface, and this question shows up in technical screens as a trie problem with a ranking twist. The interviewer checks whether you move work to the write path so reads are O(prefix length), and whether you can argue why the cached top-k per node stays correct.
What the Interviewer Expects
- Chooses a trie and explains why a sorted list or full scan is too slow per keystroke
- Caches top-k at each node so suggest is O(len(prefix))
- Argues correctness of the cache given counts only increase
- Applies the tie-break rule consistently
- Discusses memory cost and how real systems shard or precompute
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What changes if counts can decrease, for example decaying popularity or removed queries?
- How would you blend personalization into suggestions without a per-user trie?
- How would you serve this across regions with hourly rebuilt popularity?
- How would you handle 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 ProblemsSample Answer
Requirements
Two operations. record increments a query's count (it may be new). suggest(prefix) returns at most 3 queries with that prefix, ordered by count descending then lexicographically. Reads vastly outn...
High-Level Design
Store queries in a trie. Each node keeps a short list top of the best k queries in its subtree. On record, I walk the query's characters and at each node remove the query if present, append it, so...