CodePark/ problems / Top K Most Frequent Numbers
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Heaps and top-k

Top K Most Frequent Numbers

mediumabout 20 minutes in an interview

Count how often each number shows up in nums. Return the k numbers with the highest counts.

  • The result can be in any order.
  • There's never a tie at the cut-off, so only one set of k numbers is correct.
  • k is at least 1 and at most the number of different values in nums.
  • nums can hold up to 100,000 numbers, and some can be negative.
Input: nums = [4, 4, 4, 6, 6, 9], k = 2 Output: [4, 6]4 appears three times and 6 appears twice. [6, 4] is also correct.
Input: nums = [-2], k = 1 Output: [-2]