Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top-K Frequent Errors From Logs

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Top-K Frequent Errors From Logs. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

SAP Cloud ALM receives a stream of error messages from monitored applications. Given an iterable of incoming error-message strings, return the k most frequent messages efficiently.

The result must be ordered by decreasing frequency. If two messages have the same frequency, order them by reverse lexicographic order, with the lexicographically larger message first.

Formal Specification

Implement top_k_errors(logs, k).

  • logs is an iterable of strings. It may be a list, tuple, or generator.
  • k is a positive integer.
  • Return a list of [message, frequency] pairs.
  • Return at most k pairs if fewer than k distinct messages occur.
  • A message is counted once for each occurrence in logs.

Use a frequency map to aggregate counts and a bounded min-heap to avoid sorting every distinct message when k is small.

Constraints

  • 0 <= len(logs) <= 10^6
  • 1 <= k <= 10^5
  • Each message contains 1 to 200 characters
  • There are at most 10^6 distinct messages
  • Messages contain printable ASCII characters

Function Signature

def top_k_errors(logs, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output