Skip to content

Top k frequent elements

MediumPython 3HeapsPriority queuesHash tablesArrays

You are given a list of integers nums and an integer k. Return the k most frequent values in nums.

The result must be deterministic: return the values sorted by decreasing frequency, breaking ties with the smaller value first.

Constraints:
  - 1 <= len(nums) <= 10^5
  - 1 <= k <= number of distinct values in nums
Examples:
  [1, 1, 1, 2, 2, 3], k = 2  -> [1, 2]
  [1], k = 1                 -> [1]
  [4, 4, 5, 5, 6], k = 2     -> [4, 5]   (4 and 5 tie at 2; 4 is smaller)
  [3, 0, 1, 0], k = 1        -> [0]

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…