← Questions
Top K most active users from chat logs
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Dec 2025. It tests heaps, hash maps and quickselect.
A chat log is a list of messages, each recorded as the id of the user who sent it. A user's activity is the number of messages they sent. Return the k most active users. Show at least two ways to pick the top k, with their costs.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
top_k_active(messages: list[str], k: int) -> list[str]— thekusers with the most messages, most active first, ties broken by smaller user id. If there are fewer thankdistinct users, return them all.
Example
messages = ["bo", "al", "cy", "al", "bo", "al", "di"]
top_k_active(messages, 2) -> ["al", "bo"] # al 3, bo 2
top_k_active(messages, 3) -> ["al", "bo", "cy"] # cy and di tie at 1; "cy" < "di"
Constraints
-
nmessages, up to millions;udistinct users;1 <= k. - Aim to beat sorting every user when
kis much smaller thanu.
Clarifying questions
- Is the tie-break required, or may ties come out in any order?
- Should the result be ordered, or just the set of
kusers? - Does the log fit in memory, or does it stream?
- Is this a one-off or a query repeated as messages arrive?
What a strong answer covers
- Count with a hash map, O(n).
- Sort all users by
(-count, id): O(u log u). - A min-heap of size
kkeyed by(count, reversed id): O(u log k), and the comparator that keeps the tie-break right. - Quickselect: O(u) on average, then sort only the
kwinners; its worst case and why it is rarely an issue. - Bucket sort by count when counts are bounded by
n: O(n + u). - Tests:
klarger than the number of users, all users tied, a single user.
Follow-ups
- Messages stream in and the top
kis queried constantly. - The log is spread across many machines (count locally, merge counts, then select; why per-machine top
kis not enough). - Only approximate counts fit in memory (Count-Min sketch with a heap, or Misra-Gries).
Where it's asked
- Google · First round: coding · Last asked Dec 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
