
Problem
Solution
Submissions
Top K Frequent Elements
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to find the k most frequent elements in an array. Return the answer in any order.
Example 1
- Input: nums = [1,1,1,2,2,3], k = 2
- Output: [1,2]
- Explanation: The elements 1 and 2 appear most frequently. 1 occurs 3 times and 2 occurs 2 times.
Example 2
- Input: nums = [1], k = 1
- Output: [1]
- Explanation: There's only one element, so it's the most frequent by default.
Constraints
- 1 ≤ nums.length ≤ 10^5
- -10^4 ≤ nums[i] ≤ 10^4
- k is in the range [1, the number of unique elements in the array]
- It is guaranteed that the answer is unique
- Time Complexity: O(n log n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a dictionary to count the frequency of each element
- Consider using a priority queue (heap) to find the k most frequent elements
- Alternatively, use bucket sort for O(n) time complexity
- Sort the elements based on their frequency
- Return the top k elements