Top K Frequent Elements

35 min · topKFrequent()

Raw event logs are noisy. A short list of the values that appear most often is much more useful.

Given an integer array nums and an integer k, return the k values with the highest frequency — the number of times a value appears. You may return those values in any order.

A few ground rules:

  • k never exceeds the number of distinct values in nums.
  • The answer is unique. When one value sits just inside the top k and another sits just outside it, the inside value always appears more often.
  • The output contains values from nums, not their positions or their frequencies.

Constraints

  • 1 <= nums.length <= 100_000
  • 1 <= k <= the number of distinct values in nums
  • -1_000_000_000 <= nums[i] <= 1_000_000_000
  • The set of k most frequent values is unique.

Hints

Count before you rank

First build a map from each value to the number of times it appears. Sorting those map entries by their counts already gives you a correct baseline.

A frequency has a ceiling

No value can appear more than nums.length times. What if index f of an array held every value whose frequency is exactly f?

Walk the buckets backwards

Fill the frequency buckets in one pass over the count map, then scan from the largest possible frequency down. Stop as soon as you've collected k values.

Follow-up

Could you keep only the current top k values if the input arrived as a stream and there were too many distinct values to bucket at once?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  1,
  1,
  2,
  2,
  3
]
k = 2
Expected
[
  1,
  2
]
Why
1 appears three times and 2 appears twice

Example 2

ready
Input
nums = [
  4,
  -2,
  -2,
  4,
  9,
  4,
  4
]
k = 1
Expected
[
  4
]
Why
4 has the single highest frequency

Example 3

ready
Input
nums = [
  -1,
  8,
  5,
  8,
  8,
  -1
]
k = 3
Expected
[
  8,
  -1,
  5
]
Why
k includes all three distinct values

Interview signal

Asked at

AmazonMetaYelpUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite