Top K Frequent Error Codes
Given a list of error codes collected from log lines, return the k error codes that occur most frequently.
Order the result by decreasing frequency. If two error codes have the same frequency, place the lexicographically smaller error code first.
Method Signature
List<String> topKFrequentErrorCodes(List<String> errorCodes, int k)
errorCodes contains the error code from each log line.
k is the number of distinct error codes to return.
- Returns the
k most frequent error codes in deterministic order.
Ordering Rules
- An error code with a higher frequency appears first.
- Error codes with the same frequency are ordered in ascending lexicographical order.
- Each error code appears at most once in the returned list.
Constraints
1 ≤ errorCodes.size() ≤ 100,000
1 ≤ errorCodes.get(i).length() ≤ 100
errorCodes.get(i) is a non-empty error code.
1 ≤ k ≤ the number of distinct error codes in errorCodes.
- Lexicographical comparison is case-sensitive.
Examples
Example 1
topKFrequentErrorCodes(errorCodes = List.of("E404", "E500", "E404", "E403", "E500", "E404"), k = 2)
Output: List.of("E404", "E500")
"E404" occurs three times and "E500" occurs twice.
Example 2
topKFrequentErrorCodes(errorCodes = List.of("DB_ERROR", "AUTH_ERROR", "TIMEOUT", "AUTH_ERROR", "DB_ERROR", "TIMEOUT", "CACHE_ERROR"), k = 3)
Output: List.of("AUTH_ERROR", "DB_ERROR", "TIMEOUT")
The three returned codes occur twice each, so they are ordered lexicographically.
Example 3
topKFrequentErrorCodes(errorCodes = List.of("NETWORK", "DISK", "NETWORK", "MEMORY", "DISK", "NETWORK", "MEMORY", "MEMORY"), k = 1)
Output: List.of("MEMORY")
"MEMORY" and "NETWORK" both occur three times. Since "MEMORY" is lexicographically smaller, it is returned.