Top K Most Frequent Search Queries with Alphabetical Tie-Breaks
Last updated: November 29, 2026
Quick Overview
Given a list of search queries and an integer k, return the k most frequent queries ordered by frequency descending, breaking ties by lexicographic order.
0
0
0 solved
Given a list of search queries and an integer k, return the k most frequent queries ordered by frequency descending, breaking ties by lexicographic order.
A Google phone screen question framed around trending queries. The interviewer checks that you count with a hash map, select efficiently with a size-k heap instead of a full sort, and get the tie-breaking order exactly right, which is where most bugs appear.
What the Interviewer Expects
- Counts with a hash map in O(n)
- Explains full sort O(m log m) versus heap O(m log k)
- Handles tie-breaking correctly with a custom key
- Returns results in the required order
- Discusses approximate counting for unbounded streams
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
- The stream is unbounded and memory is limited; how do you approximate top k?
- Report top k over a sliding one-hour window.
- Can you do it in O(n) average time with bucket sort or quickselect?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: list of strings
queries, integer k at most the number of distinct queries. - Output: k strings, highest count first; equal counts ordered alphabetically....
High-Level Design
Count with Counter. Then select the top k. A clean way in Python is heapq.nsmallest(k, counts, key=lambda q: (-counts[q], q)), which maintains a heap of size k internally, so selection costs O(m l...