You are given a list of whole numbers, nums, and a number k. Some values show up more often than others.
Return the k values that appear the most times. Each value goes in the answer once, in any order. The input is chosen so the answer is never ambiguous: there is no tie for the last place.
Example 1
Input: nums = [7, 3, 7, 5, 3, 7], k = 2 Output: [7, 3] Why: 7 appears three times, 3 twice, 5 once
2 more examples and the constraints
Example 2
Input: nums = [-2, -2, 4, 4, 4, 9, -2, 4], k = 1 Output: [4] Why: 4 appears four times, more than any other value
Example 3
Input: nums = [6], k = 1 Output: [6] Why: the only value is the most frequent one
Constraints
- 1 ≤ length of nums ≤ 100,000
- −10,000 ≤ each number ≤ 10,000
- 1 ≤ k ≤ how many distinct values nums holds
- Exactly one set of k values is the answer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count, then sortO(n log n)
- Min-heap of size kO(n log k)
- Bucket by countO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Count, then sort | O(n log n) | Passes; fails the follow-up | |
| Min-heap of size k | O(n log k) | Good when k is small | |
| Bucket by count | O(n) | Best; no sorting at all |
n = length of nums, k = how many values to return.
Edge cases to test
- One number. [6] with k = 1 gives [6].
- k takes every value. [1, 2, 2, 3, 3, 3] with k = 3 returns all three distinct values.
- Every number the same. [5, 5, 5, 5] has a count of 4, which lands in the last bucket, index n. The array needs n + 1 slots.
- Negative values. Values are keys in the map, never array indexes, so −3 works the same as 3.
- Ties below the cut. In [8, 8, 8, 1, 2, 3, 4] with k = 1, four values tie at one each, but only 8 is needed.
Common mistakes
- Making only n buckets, so a value that fills the whole list has no bucket.
- Using the values as bucket indexes instead of their counts, which breaks on negatives.
- Keeping a max-heap of every value instead of a min-heap of k, which is no faster than sorting.
How to talk through it
- 1Clarify. Can there be a tie for the last place? Does the order of the answer matter? Can values be negative?
- 2Give the simple version. Count with a hash map, sort by count, take k. Say it is O(n log n).
- 3Trim the work. Only k values matter: a min-heap of size k makes it O(n log k).
- 4Use the bound on counts. A count is at most n, so bucket by count and walk from the top for O(n).
- 5Test out loud. Run a single number, all-equal values and k equal to the number of distinct values.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?