Top K Search Suggestions From A Weighted Query Log

Last updated: November 29, 2026

Quick Overview

Build a structure over a log of (query, count) that returns the k most frequent queries starting with a given prefix, and supports incrementing a query's count as new searches arrive.

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

0

0

0 solved


Build a structure over a log of (query, count) that returns the k most frequent queries starting with a given prefix, and supports incrementing a query's count as new searches arrive.

Search Suggest is the dropdown under the Yandex search box and must answer every keystroke in a few milliseconds. In an onsite coding section the interviewer wants a trie with cached top-k lists and a clear trade-off between query time and update cost.

What the Interviewer Expects
  • Use a trie keyed by characters
  • Cache the top k at each node so a lookup costs O(len(prefix))
  • Update the cached lists along the path when a count changes
  • Define tie-breaking (count desc, then lexicographic)
  • Discuss memory and the cost of updates
Key Topics to Cover
trie
top-k
caching
prefix search
autocomplete
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 shard this structure across machines for a national search engine?
  • How do you add freshness so a breaking news query rises within minutes?
  • How would you support typo tolerance or keyboard layout switching (Latin typed instead of Cyrillic)?
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

Operations: suggest(prefix) returns up to k queries by count descending, ties broken alphabetically; add(query, delta) increases a count. Reads vastly outnumber writes, and reads must be fast....

High-Level Design

A trie where every node stores a sorted list of at most k (-count, query) pairs for the queries in its subtree. A lookup walks the prefix and returns that list. An update walks the query path (len...


Submit Your Answer
Markdown supported

Related Questions