iq.lab
Python starts when a code cell comes near or you run one
mediumHash maps and setsSorting target 25 min

Top k frequent elements

You get a list of integers nums and a whole number k. Return a list of the k values that appear most often in nums, each value once.

The input always has a clean cut: each of those k values appears more often than every value left out, so exactly one answer exists. Return its k values in any order.

Example 1
Inputnums = [4, 4, 1, 4, 2, 2, 3], k = 2Output[4, 2]

4 appears three times and 2 twice. 1 and 3 appear once each.

Example 2
Inputnums = [7], k = 1Output[7]

7 is the only value, so it is the most frequent.

Example 3
Inputnums = [5, -1, 5, -1, 8], k = 2Output[5, -1]

5 and -1 appear twice each, 8 once. [-1, 5] is also correct.

Constraints
  • 1 ≤ len(nums) ≤ 105

  • -104 ≤ nums[i] ≤ 104

  • 1 ≤ k ≤ the number of distinct values in nums

  • The answer is unique: there is no tie at the cut.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.