KatInterview

Most Frequent Log Error Codes in Time Interval

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & HashingArrays & HashingSortingHash Table

Last updated

Filter log entries within a half-open time interval, compute occurrence frequencies, and retrieve the top k error codes sorted by frequency and string order.

You are analyzing a sequence of system events. Each event is recorded as a dictionary containing three keys:

  • "timestamp" (integer): the epoch time of the event.
  • "error_code" (string): the identifier string of the error.
  • "severity" (integer): the severity level of the issue.

Given a list of system events logs, a time range defined by bounds start_time and end_time, and an integer k, extract the top k most frequent error codes among events occurring in the half-open interval [start_time, end_time).

Ranking Rules

  1. Order error codes primarily by their total count within the specified window in descending order (highest frequency first).
  2. If two or more error codes share the same frequency, order them lexicographically (ascending alphabetical order).
  3. If the total count of distinct qualifying error codes is less than k, return all qualifying error codes in the specified order.

Constraints

  • $1 \le N \le 10^5$, where $N$ is the length of logs.
  • $0 \le \text{timestamp} \le 10^9$ for all entries.
  • Each error_code string has length between $1$ and $10$.
  • $k \ge 0$.
  • The time interval is half-open: a log entry at timestamp is valid if and only if $\text{start_time} \le \text{timestamp} < \text{end_time}$.

Examples

Example 1

Input: get_top_errors([{'timestamp': 10, 'error_code': '404', 'severity': 1}, {'timestamp': 15, 'error_code': '500', 'severity': 2}, {'timestamp': 20, 'error_code': '404', 'severity': 1}], 10, 20, 1)

Output: ['404']

Example 2

Input: get_top_errors([{'timestamp': 1, 'error_code': 'A', 'severity': 3}, {'timestamp': 2, 'error_code': 'B', 'severity': 1}, {'timestamp': 3, 'error_code': 'A', 'severity': 2}, {'timestamp': 4, 'error_code': 'C', 'severity': 5}], 1, 5, 2)

Output: ['A', 'B']

Example 3

Input: get_top_errors([{'timestamp': 5, 'error_code': 'timeout', 'severity': 1}, {'timestamp': 10, 'error_code': '500', 'severity': 2}], 5, 10, 5)

Output: ['timeout']

Hints

Hint 1

Filter the log entries first to keep only those whose timestamps satisfy `start_time <= timestamp < end_time`.

Hint 2

Use a hash map or Counter to tally the occurrences of each unique error_code within the filtered window.

Hint 3

Sort the unique error codes using a tuple key `(-count, error_code)` so that higher counts come first and identical counts are broken by ascending string order.