Search Bar Autocomplete Ranked by Historical Query Counts

Last updated: November 29, 2026

Quick Overview

Implement an autocomplete system seeded with past queries and their counts. Each call input(c) adds a character to the current query and returns the top three past queries with that prefix, ranked by count then alphabetically; the character '#' ends the query, records it with count plus one, and returns an empty list.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Implement an autocomplete system seeded with past queries and their counts. Each call input(c) adds a character to the current query and returns the top three past queries with that prefix, ranked by count then alphabetically; the character '#' ends the query, records it with count plus one, and returns an empty list.

Facebook search typeahead ranks suggestions by popularity, and this design-plus-code question mirrors it at small scale. Interviewers look for stateful handling of the in-progress query, correct tie-breaking, and a sensible split between work done on insert and work done per keystroke.

What the Interviewer Expects
  • Keep the current node and current prefix as state between calls
  • Rank by highest count, then lexicographic order
  • On '#', record the query (new or existing) and reset state
  • Once the prefix leaves the trie, return empty lists until '#'
  • Discuss caching top results per node versus computing on demand
Key Topics to Cover
trie
stateful API
ranking
heap
typeahead
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 precompute top three per node and keep it correct on updates?
  • How would you blend in personalization like friends' names?
  • How would you shard this for billions of queries?
  • How would you age out old queries?
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
  • Constructor: sentences and times (parallel lists). Characters are lowercase letters and spaces.
  • input(c): if c == '#', store the typed query with count +1, reset, return []. Otherwise ex...
High-Level Design

Store queries in a trie. Each node keeps the set of full sentences that pass through it, and a global dict holds counts. Ranking at a node is then heapq.nsmallest(3, node.sentences, key=(-count, s))...


Submit Your Answer
Markdown supported