easyHeap / Priority QueuePure DSA~18 min
Top Error Codes
An incident dashboard surfaces the k most frequent error codes from the last hour of logs. Given the list of error codes seen and an integer k, return the k codes that occurred most often, in any order.
Problem
Given an array codes of length n and an integer k, return the k most frequent values. It is guaranteed the answer is unique (no ties span the k-th boundary).
Input
Integers n (1 ≤ n ≤ 10^5) and k (1 ≤ k ≤ number of distinct codes), and an array codes of n integers.
Output
An array of k integers — the most frequent codes (any order).
Constraints
- 1 ≤ k ≤ number of distinct values ≤ n ≤ 100,000
- The k-th boundary is unambiguous
- Output order does not matter
Examples
Example 1
Input
codes = [500, 500, 404, 500, 404, 503], k = 2
Output
[500, 404]
500 appears 3 times, 404 twice, 503 once. The two most frequent are 500 and 404.
Example 2
Input
codes = [429], k = 1
Output
[429]
Only one code; it is the most frequent.