K most frequent values
Given a list of integers and an integer k, return the k most frequent values, ordered from most frequent to least frequent. When two values occur the same number of times, the smaller value comes first. You may assume k is at least 1 and at most the number of distinct values. Example: nums = [4, 1, 4, 2, 2, 4], k = 2 gives [4, 2] — 4 appears three times and 2 appears twice, so 1 (seen once) misses the cut.
Implement
top_frequent(nums: list[int], k: int) → list[int]Examples
in
[[4,1,4,2,2,4],2]out[4,2]What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 15 min
solution.py
InputExpectedGot
[[4,1,4,2,2,4],2][4,2]not run yetsample