medium +25 pts

Top K Frequent Elements

Return the k most frequent numbers from a list, in any order.

Write a function `top_k_frequent(nums, k)` that takes a list of integers `nums` and an integer `k`. It should return a list of the `k` most frequent numbers in `nums`. The order of the returned elements does not matter. If there is a tie in frequency, any of the tied elements may be chosen. It is guaranteed that `k` is in the range `[1, the number of unique elements in nums]`.

Constraints

- `1 <= nums.length <= 10^5` - `-10^4 <= nums[i] <= 10^4` - `1 <= k <= number of unique elements in nums` - The returned list can be in any order. - Time complexity should be O(n log k) or better. - Space complexity: O(n) where n is the number of unique elements.

Example

```python
# Example 1
nums = [1,1,1,2,2,3]
k = 2
print(top_k_frequent(nums, k))  # Output: [1, 2] (any order)

# Example 2
nums = [1]
k = 1
print(top_k_frequent(nums, k))  # Output: [1]

# Example 3
nums = [4,4,4,5,5,6,6,6,7]
k = 3
print(top_k_frequent(nums, k))  # Output could be [4, 6, 5] (any order)
```
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Count frequencies using a dictionary.
Use a min-heap of size k to keep the top k most frequent elements.
Alternatively, you can use `heapq.nlargest` with a key that accesses the frequency.
Remember that the returned list can be in any order, so sorting is not required.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.