Most Frequent Log Error Codes in Time Interval
Arrays & HashingAuto-graded · 19 test casesLast 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
- Order error codes primarily by their total count within the specified window in descending order (highest frequency first).
- If two or more error codes share the same frequency, order them lexicographically (ascending alphabetical order).
- 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_codestring has length between $1$ and $10$. - $k \ge 0$.
- The time interval is half-open: a log entry at
timestampis 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires a combination of filtering, aggregation, and custom sorting.
-
Filtering & Aggregation: Iterate through
logsand filter for entries that satisfy the conditionstart_time <= entry["timestamp"] < end_time. For each valid log, accumulate the count of itserror_codeusing a hash map (or Python'scollections.Counter). -
Custom Sorting: To sort the unique error codes according to the problem requirements:
- Sort by count in descending order.
- For ties, sort by the error code string in ascending order.
In Python, sorting tuples
(-count, code)handles both rules simultaneously because tuples are compared element-by-element. Negating the count reverses its sort direction, while leaving the string unchanged preserves ascending order. -
Truncation: Take the first
kelements of the sorted list. Python's slice notation[:k]safely handles cases wherekis larger than the number of unique error codes available.
Complexity
- Time Complexity: $\mathcal{O}(N + U \log U)$, where $N$ is the number of logs in
logsand $U$ is the number of unique error codes present in the target window ($U \le N$). Filtering takes $\mathcal{O}(N)$, and sorting $U$ unique keys takes $\mathcal{O}(U \log U)$. - Space Complexity: $\mathcal{O}(U)$ auxiliary space to store the frequency counts and unique error code strings.
from collections import Counter
from typing import List, Dict
def get_top_errors(logs: List[dict], start_time: int, end_time: int, k: int) -> List[str]:
# 1. Filter logs in time window [start_time, end_time) and count error frequencies
counts = Counter(
entry["error_code"]
for entry in logs
if start_time <= entry["timestamp"] < end_time
)
# 2. Sort keys by frequency (descending) then string value (ascending)
ranked = sorted(counts.keys(), key=lambda code: (-counts[code], code))
# 3. Return the top k codes
return ranked[:k]