Tutorialspoint
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)
Priority QueueTutorialspointSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a dictionary to count the frequency of each element in the array.
 Step 2: Create an array of lists (buckets) where the index represents the frequency.
 Step 3: Iterate through the frequency map and add each number to the corresponding bucket.
 Step 4: Iterate through the buckets from highest frequency to lowest.
 Step 5: Add elements from each bucket to the result list until we have k elements.
 Step 6: Return the result list converted to an array.
 Step 7: This bucket sort approach gives us O(n) time complexity.

Submitted Code :