Top-K most active accounts

Python data engineering interview problem. Difficulty: intermediate. Pattern: Sorting. About 15 minutes. Part of the Pro drill bank.

An activity feed lists account ids. Support wants the k accounts that appear most often so they can investigate noisy customers first.

A fraud team wants the k accounts that appear in the most events, for a first look. Count how often each account appears in events, and return the k accounts with the highest counts. For equal counts, put the account that comes first alphabetically first. Return only the account names. Write top_k_accounts(events, k). In ['a','b','a','c','b','a'] the counts are a 3, b 2, c 1. For k = 2 the answer is ['a', 'b']. With no events the answer is []. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Count the events for each account.
  • Rank by count, highest first.
  • Break ties alphabetically.
  • Return only the first k names.

Constraints

  • events is a list of account names.
  • k can be larger than the number of accounts.

Examples

Input: top_k_accounts(['a', 'b', 'a', 'c', 'b', 'a'], 2) Output: ['a', 'b'] This input follows the stated rules and produces this output.

Topics: lakebench, python, sorting.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Top-K most active accounts

Interview-style drill: Given a list of account activity events, return the K accounts with the most events.

Return the top-k most frequent accounts.