Top K Frequent
Python data engineering interview problem. Difficulty: advanced. Pattern: Heaps. About 18 minutes. Part of the Pro drill bank.
Return the k most frequent numbers, sorted for stability. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A report needs the most common ids, but its output must be stable so 2 runs can be compared. Return the k most frequent values, then sort those selected values in ascending order. Frequency chooses the group; numeric order controls the final display. Write top_k_frequent(nums: list, k: int) -> list. In [1, 1, 1, 2, 2, 3], the two most frequent values are 1 and 2, so the stable result is [1, 2]. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Count every value.
- Select exactly k values unless fewer unique values are available.
- Sort the selected values ascending.
Constraints
- Duplicates count toward frequency and k is positive.
- Return a list of values, not (value, count) pairs.
Examples
Input: top_k_frequent([1, 1, 1, 2, 2, 3], 2) Output: [1, 2] 1 and 2 are most frequent; sorted.
Topics: lakebench, python, frequency, heap.
More Python interview questions · All interview problems · Learn data engineering
Top K Frequent
Interview-style drill: Return the k most frequent numbers, sorted for stability.
Implement `top_k_frequent(nums: list, k: int) -> list`. Return the k most frequent values sorted ascending for stable output. Example: `[1, 1, 1, 2, 2, 3], 2` → `[1, 2]`. Keep the harness.