Skip to main content

Top K Frequent Elements Extractor

easy
HeapHash TableSortingCountingTop K HeapHashmap Lookup
Asked atAmazonGoogleMicrosoftMetaUber

Problem Description

Given an integer array `values` and an integer `k`, return the `k` most frequently occurring elements. You may return the answer in any order.

**Example 1:**
```
Input: values = [3, 1, 3, 2, 1, 3], k = 2
Output: [3, 1]
Explanation: 3 appears 3 times, 1 appears 2 times. These are the top 2.
```

**Example 2:**
```
Input: values = [7, 7, 8, 8, 9, 9, 9], k = 1
Output: [9]
Explanation: 9 appears 3 times, more than any other element.
```

Constraints

  • 1 <= values.length <= 10^5
  • values[i] is in the range [-10^4, 10^4]
  • 1 <= k <= number of unique elements in values
  • The answer is guaranteed to be unique.

Follow-up

Can you solve this in O(n) time using bucket sort? What trade-offs does that introduce?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.