Top k frequent elements
The problem
Given an integer array nums and an integer k, return any order list of the k most frequent elements in nums.
Your solution must run in better than O(n log n) time, where n = nums.length.
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Explanation: 1 appears 3 times, 2 appears 2 times, 3 appears once. The two most-frequent elements are 1 and 2.
**Input: **nums = [4,4,6,6,7], k = 2 Output: [4,6] Explanation: 4 and 6 both occur twice (highest), 7 occurs once.
Input: nums = [-1,-1,-2,-2,-2,-3], k = 1
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
- 1 ≤ k ≤ number of distinct elements in nums
- The answer is guaranteed to be unique.
cpp
class Solution {
public:
vector<int> topKFrequent(const vector<int>& nums, int k) {
// Your code goes here
}
};java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// Your code goes here
}
}python
class Solution:
def topKFrequent(self, nums, k):
# Your code goes herejavascript
class Solution {
topKFrequent(nums, k) {
// Your code goes here
}
}csharp
class Solution
{
public IList<int> TopKFrequent(int[] nums, int k)
{
// Your code goes here
}
}go
func topKFrequent(nums []int, k int) []int {
// Your code goes here
}Stuck? Show a way to structure it+
- 01Count each value's frequency.
- 02Place values by frequency in buckets or use a size-k heap.
- 03Read largest frequencies until k values are collected.
- 04State why the chosen method meets the bound.
Reference answer
Then expect these follow-ups
How would you maintain the top k in a live stream?
Tests: heap maintenance
How do ties affect output when uniqueness is not guaranteed?
Tests: specification
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question
- Calculate the trapped rainwater between bars in a given array.
- Find a triplet in an array with a given sum.
- Print all combinations of numbers from 1 to n that sum to n.
- Find the number of rotations in a circularly sorted array.
- Find all permutations of a given string.
- Check if two given binary trees are identical.