← Questions

Top K most active users from chat logs

0
GoogleCodingLast asked Dec 2025

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] — the k users with the most messages, most active first, ties broken by smaller user id. If there are fewer than k distinct 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

  • n messages, up to millions; u distinct users; 1 <= k.
  • Aim to beat sorting every user when k is much smaller than u.

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 k users?
  • 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 k keyed 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 k winners; its worst case and why it is rarely an issue.
  • Bucket sort by count when counts are bounded by n: O(n + u).
  • Tests: k larger than the number of users, all users tied, a single user.

Follow-ups

  • Messages stream in and the top k is queried constantly.
  • The log is spread across many machines (count locally, merge counts, then select; why per-machine top k is 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

heaps · hash maps · quickselect

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